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
import numpy as np
import torch.nn as nn
from math import ceil
from torch.autograd import Variable
from ptsemseg import caffe_pb2
from ptsemseg.models.utils import *
from ptsemseg.loss import *
pspnet_specs = {
'pascalvoc':
{
'n_classes': 21,
'input_size': (473, 473),
... | ptsemseg/models/pspnet_two_heads.py | MIT | 15,962 | 3a0d629228306f8fb35723cd5a7e1b2055af78d3 | Python | py | |
# stdlib
from os import listdir
from os.path import join
# third party
from PIL import Image
import torch.utils.data as data
def is_image_file(filename):
return any(filename.endswith(extension) for extension in [".png", ".jpg", ".jpeg"])
def load_img(filepath):
img = Image.open(filepath).convert("YCbCr")
... | examples/duet/super_resolution/original/dataset.py | Apache-2.0 | 1,128 | 24a043ff35045caf464743c7255b425cd6187261 | Python | py | |
'''
Function:
模型训练
Author:
Charles
微信公众号:
Charles的皮卡丘
'''
import os
import torch
import argparse
import torch.nn as nn
from torch.utils.data import DataLoader
from modules import Backbone, ImageFolder, LifeGame, Logger, touchdir
'''命令行参数解析'''
def parseArgs():
parser = argparse.ArgumentParser(descripti... | deeplearningtoys/CNNLifeGame/train.py | Apache-2.0 | 3,206 | 3a0d6699b1a10bf0cee804df6ee6899698b4a875 | Python | py | |
import argparse
import datetime
import logging
import math
import random
import time
import torch
from mmcv.runner import get_dist_info, get_time_str, init_dist
from os import path as osp
import sys
sys.path.append('.')
from basicsr.data import create_dataloader, create_dataset
from basicsr.data.data_sample... | basicsr/train.py | MIT | 9,249 | 3a0d7779b36c339f697a1e837ceee6c405484038 | Python | py | |
#!/usr/bin/env python3
# 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 logging
import math
from functools import reduce
import crypten
import crypten.communicator as comm
import tor... | crypten/gradients.py | MIT | 59,750 | 5f45ee3ee09c8ec7bdcb18af9050e1dddb466a10 | Python | py | |
import logging
from typing import Dict, Tuple, List, Any, Union
import numpy
from overrides import overrides
import torch
from torch.nn.modules.linear import Linear
from torch.nn.modules.rnn import LSTMCell
from allennlp.common.checks import ConfigurationError
from allennlp.common.util import START_SYMBOL, END_SYMBOL... | nlpete/models/copynet.py | MIT | 43,757 | 4237bda380a204216cbe5fcf74531c9a3b50f56b | Python | py | |
import argparse
import warnings
from math import ceil
from pathlib import Path
import torch
import torchvision.models.optical_flow
import utils
from presets import OpticalFlowPresetTrain, OpticalFlowPresetEval
from torchvision.datasets import KittiFlow, FlyingChairs, FlyingThings3D, Sintel, HD1K
try:
from torchvi... | references/optical_flow/train.py | BSD-3-Clause | 14,339 | fdb9e4d8d7a0a3363e5507484b374faf15046f37 | Python | py | |
import gym
import time
import torch
import warnings
import numpy as np
from copy import deepcopy
from numbers import Number
from typing import Dict, List, Union, Optional, Callable
from tianshou.policy import BasePolicy
from tianshou.exploration import BaseNoise
from tianshou.data.batch import _create_value
from tians... | tianshou/data/collector.py | MIT | 17,814 | 428ff6c46fe13d68b318354a764d6333344a8685 | Python | py | |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue May 4 20:55:24 2021
@author: trduong
"""
import pandas as pd
import numpy as np
import logging
import yaml
import pyro
import torch
import pyro.distributions as dist
import sys
from sklearn.linear_model import LinearRegression
from sklearn import pr... | src/run_law_data.py | MIT | 5,520 | 03a676b8e2679bfb2847da772358a67163ae74eb | Python | py | |
"""
This code stems from https://github.com/kuangliu/pytorch-fpn/blob/master/fpn.py
Copied on: 30.01.2019
"""
__all__ = ['ResNet', 'resnet18', 'resnet34', 'resnet50', 'resnet101',
'resnet152']
model_urls = {
'resnet18': 'https://download.pytorch.org/models/resnet18-5c106cde.pth',
'resnet34': 'http... | reid/scripts/triplet_reid/models/panoptic/resnet_fpn.py | MIT | 6,230 | 3a0e260735a501579299411062a38e21198d4d47 | Python | py | |
from __future__ import print_function
import argparse
import sys
sys.path.append(".")
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torch.optim.lr_scheduler import StepLR
from torchvision import transforms
from learn.utils import MNIST
class Net(nn.Module):
... | learn/train.py | MIT | 5,222 | 3a0e3d02f5b10f5e3e222c3bc5bdac5980bcd26c | Python | py | |
"""RefineNet-LightWeight
RefineNet-LigthWeight PyTorch for non-commercial purposes
Copyright (c) 2018, Vladimir Nekrasov (vladimir.nekrasov@adelaide.edu.au)
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are m... | src/train_res152.py | BSD-2-Clause | 19,094 | 3a0e3d44ff897db70697ccd1c56ad8a2ab9c0e03 | Python | py | |
from ..builder import DETECTORS
from .local_faster import LocalFasterRCNN
import numpy as np
import torch
import random
@DETECTORS.register_module()
class LocalTridentFasterRCNN(LocalFasterRCNN):
"""Implementation of `TridentNet <https://arxiv.org/abs/1901.01892>`_"""
def __init__(self,
p_si... | mmdet/models/detectors/local_trident.py | Apache-2.0 | 8,259 | 4553a0c8c41f4af083ddb5cfe6f3d7fa2e0069bf | Python | py | |
import torch.nn as nn
# class DeepClean(nn.Module):
# def __init__(self, in_channels):
# super().__init__()
# self.input_conv = nn.Sequential(
# nn.Conv1d(in_channels, in_channels, kernel_size=7, stride=1, padding=3),
# nn.BatchNorm1d(in_channels),
# ... | deepclean_prod/nn/net.py | MIT | 4,075 | e6485ad5e01a389e30e50965ab2bc06d6e8097b3 | Python | py | |
# flake8: noqa - this is until we take care of the F401 violations with respect to __all__ & sphinx
from typing import Any, Dict, List, Tuple, Union
from torch.nn import Module
from torch.optim import Optimizer
from torch.utils.data import DataLoader
import mlrun.frameworks.pytorch.callbacks
from mlrun.frameworks.py... | mlrun/frameworks/pytorch/__init__.py | Apache-2.0 | 17,834 | b270cfc5e04dbf4f67aa3fe7ed2e36a255ffab92 | Python | py | |
from __future__ import print_function
from pycocotools.coco import COCO
from pycocotools.cocoeval import COCOeval
import numpy as np
import json
import os
import time
import torch
from torch.autograd import Variable
from data.config import coco
#from data.coco import COCO_CLASSES
import pdb
class Timer(object)... | data/coco_eval.py | MIT | 4,140 | fdc13f0c9508290a7feca769c3de4e9f89f360ba | 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... | tests/accelerators/test_ddp.py | Apache-2.0 | 5,637 | 6b28640e92ab464641831777cefe591820f6474d | Python | py | |
# reference implementation of BP CIFAR10 training
import argparse
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
import torchvision.datasets as datasets
import torchvision.transforms as transforms
from torch.utils.data import DataLoader, random_split
from tqdm import tq... | fig2cde_higgs_mnist_cifar10/experiments/CIFAR10/bp_layers_cifar10_training.py | MIT | 6,865 | 5ea28ab96d3f73ef0331801c19459fca1a9e3a5a | Python | py | |
import torch
import torch.nn.functional as F
import torch.nn as nn
import math
class AGCN(nn.Module):
def __init__(self, dim_in, dim_out, cheb_k, embed_dim):
super(AGCN, self).__init__()
self.cheb_k = cheb_k
self.weights = nn.Parameter(torch.FloatTensor(cheb_k*dim_in, dim_out))
self... | save/tokyo202112_MMGCRN_c1to1_20220208114535_time_lamb00/MMGCRN.py | MIT | 12,797 | 3a0e8d69f80af66b646f1b99e753ab60b5897aac | Python | py | |
# Copyright 2021 RangiLyu.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, so... | tools/train.py | Apache-2.0 | 4,168 | 3a0e99b9099216a2affef8384e50e02b31fb83fe | Python | py | |
import numpy as np
from pathlib import Path
import shutil # to remove nonempty directory
import os
import data_generators.movingmnist_gen as mmg
import importlib
importlib.reload(mmg)
class DataSetGenerator(object):
def __init__(self,
history_size,
train_n_samples=1,
... | moving_mnist/dataset_gen.py | MIT | 6,467 | 3a0eb09700e0a064ba2aa87f8bf697c1c245cad5 | Python | py | |
import torch._C
from torch.utils import set_module
# These are imported so users can access them from the `torch.jit` module
from torch._jit_internal import (
Final,
Future,
_overload,
_overload_method,
ignore,
export,
unused,
)
from torch.jit._script import (
script,
Attribute,
... | pytorch/torch/jit/__init__.py | MIT | 1,584 | 7ceca7f52759df306f7a7bd64f8a11d13a48dc91 | Python | py | |
#!/usr/bin/env python3
import argparse
import io
import os
import time
from typing import Any, Tuple
import numpy as np
import torch
from torch.utils.data import Dataset
from torch.utils.data.dataloader import DataLoader
import pfio
def index_to_rgb(index: int) -> Tuple[int, int, int]:
return index & 255, (inde... | loader-bench/main.py | MIT | 5,390 | 3a0ec254b26becf56ad95b5ae2f42cdbd90c2426 | Python | py | |
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT license.
import contextlib
import logging
import subprocess
import time
import os
import torch
import torch.distributed as dist
import seq2seq.data.config as config
from seq2seq.inference.beam_search import SequenceGenerator
from seq2seq.u... | runtime/translation/seq2seq/inference/inference.py | MIT | 10,915 | 3a0ee35ff42b1766737840656eaf3d3d84543f2f | Python | py | |
import argparse
import json
import logging
import random
import os
from collections import defaultdict, OrderedDict
from heapq import nsmallest, nlargest
from itertools import chain
from typing import Any, Dict, List, Set, Tuple
#import apex
import numpy as np
import torch
import torch.nn as nn
from sklearn.metrics ... | eraserbenchmark/rationale_benchmark/models/encode_attend.py | MIT | 27,518 | 3a0f1faea5534b83419e017e15603637d06b523f | Python | py | |
"""
In this file one can find the implementation of helpful class and functions in order to handle the given dataset, in the
aspect of its structure.
Here is the implementation of helpful class and functions that handle the given dataset.
"""
import json
import csv
from scipy.stats import zscore
from torch import Tens... | QGCN/dataset/dataset_graphs_model.py | MIT | 13,905 | e95335cd69e639b5f834bebbc735eb73ef4f0873 | Python | py | |
"""
Classification Model
Author: Wenxuan Wu
Date: September 2019
"""
import torch.nn as nn
import torch
import numpy as np
import torch.nn.functional as F
from utils.pointconv_util import PointConvDensitySetAbstraction
class PointConvDensityClsSsg(nn.Module):
def __init__(self, num_classes = 40):
super(Poi... | point_conv_pytorch/model/pointconv.py | MIT | 1,782 | 3a0f2713b2c1430c3ae5e166a7c7b385d63228f1 | Python | py | |
import functools
import itertools
from abc import ABC
from enum import Enum
from typing import Any, Optional, Sequence, Tuple, Union
import torch
import torch.utils.hooks as hooks
from torch import Tensor
from torch.nn.modules.module import (
_global_backward_hooks,
_global_forward_hooks,
_global_forward_p... | continual/module.py | Apache-2.0 | 10,860 | 3a0f2be8caa56f213d8507267ff4d28cde2e1327 | Python | py | |
import torch
import torch.nn as nn
class RMSEuclidianLoss(nn.Module):
def __init__(self):
super(RMSEuclidianLoss, self).__init__()
def forward(self, emb_anchor, emb_other, y):
diff = emb_anchor - emb_other
dist_sq = torch.sum(torch.pow(diff, 2), 1)
dist = torch.sqrt(dist_sq)
... | src/yggdrasil/criterion.py | MIT | 1,689 | 3a0f3127713cab96c8c0bbfd2c11f60f30fbb358 | Python | py | |
import torch
from kornia.augmentation.random_generator import random_prob_generator, random_color_jitter_generator
class TestRandomProbGen:
def test_random_prob_gen(self):
torch.manual_seed(42)
batch_size = 8
halfs = random_prob_generator(batch_size=batch_size, p=.5)
expected_ha... | test/augmentation/test_random_generator.py | ECL-2.0,Apache-2.0 | 7,387 | 5e6cb7b3fd5dec9802d92a196963c73ceb1930af | Python | py | |
#
# mDKL
#
# Copyright (c) Siemens AG, 2021
# Authors:
# Zhiliang Wu <zhiliang.wu@siemens.com>
# License-Identifier: MIT
import torch
import gpytorch
from gpytorch.models import ApproximateGP
from gpytorch.variational import CholeskyVariationalDistribution
from gpytorch.variational import VariationalStrategy
from gpy... | gp_layer.py | MIT | 2,722 | 3a0f5d0a73ecf83e7d9f5c0f66e522a6d2ad5904 | Python | py | |
from model import networks
import torch, os, numpy as np, scipy.sparse as sp
import torch.optim as optim, torch.nn.functional as F
from torch.autograd import Variable
from tqdm import tqdm
from model import utils
def train(HyperGCN, dataset, T, args):
"""
train for a certain number of epochs
arguments:... | model/model.py | Apache-2.0 | 3,258 | 7c2fa1c5f287916f16ccd6ac205698017ce92ed6 | Python | py | |
import torch
import torch.nn as nn
import math
import torch.utils.model_zoo as model_zoo
__all__ = ['resnet20_sw', 'resnet32_sw', 'resnet44_sw', 'resnet56_sw']
NUM_CLASSES = 10
def swish(x):
return torch.sigmoid(x) * x
def conv3x3(in_planes, out_planes, stride=1):
"""3x3 convolution with padding"""
retur... | models/resnet_cifar10_swish.py | Apache-2.0 | 4,326 | 4b79c4f092979d2f9d863f4b1cced971f2bc9619 | Python | py | |
#!/usr/bin/env python
# coding=utf-8
# Copyright 2021 The HuggingFace Inc. team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LI... | examples/pytorch/language-modeling/run_clm_no_trainer.py | Apache-2.0 | 25,835 | 3435ea2ecdbd24360cbffae7b19c394b92f9a619 | Python | py | |
import copy
from collections import defaultdict
from typing import Any, Dict, List, Tuple, Type, Union, no_type_check
import numpy as np
import torch
from torch import nn
class SaveHook:
def __init__(self) -> None:
self.saved: List[Any] = []
@no_type_check
def __call__(self, *args: Any, **kwarg... | src/whitespace_repair/utils/hooks.py | Apache-2.0 | 2,325 | 3a0f83aa461470bfa9479c434ed8c3aa91214cb7 | Python | py | |
import numpy as np
import scipy.stats
import torch
from torch import nn
from torch.nn import functional as f
from torchvision import models
from utils import init_embedding_, compute_wordsim_rho
class SkipGramModel(nn.Module):
def __init__(self, vocabulary_size, dimension):
super().__init__()
se... | model.py | MIT | 1,634 | 4b1858c9e4793543e97cb2be5a73b7d865942a9a | Python | py | |
import time
import imageio
import ntpath
import copy
import os
import librosa
import numpy as np
from sklearn.cluster import KMeans
from collections import OrderedDict
import torch
from torch.autograd import Variable
from torch.utils.tensorboard import SummaryWriter
from options.test_options import TestOptions
from... | Cal_Quanti_Center.py | MIT | 1,575 | 3a0f89ae382426f2d53c532f856764435dda2c59 | Python | py | |
# Copyright (c) 2020 NVIDIA CORPORATION.
# Copyright (c) 2018-2020 Chris Choy (chrischoy@ai.stanford.edu).
#
# Permission is hereby granted, free of charge, to any person obtaining a copy of
# this software and associated documentation files (the "Software"), to deal in
# the Software without restriction, including wit... | MinkowskiEngine/__init__.py | MIT | 3,581 | 12fbc73f246cb7716a0eec516e8d920c7d0a3079 | Python | py | |
import os
import json
import argparse
import torch
import torchaudio
import torch.nn.functional as F
from torch.utils.tensorboard import SummaryWriter
from torch.utils.data import DataLoader
import pandas as pd
from utils import (ASRModel, greedy_decode, AudioDataset, TextTransform, data_processing)
if __name__ == '... | infer.py | Apache-2.0 | 2,723 | 3a0f9ba0db39e15116298580c2067097b03ec831 | Python | py | |
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
from typing import Any, Dict, List
import torch
from .lr_scheduler import WarmupCosineLR, WarmupMultiStepLR, WarmupMultiGammaLR
def build_optimizer(cfg, model: torch.nn.Module) -> torch.optim.Optimizer:
"""
Build an optimizer from config... | solver/OptimizerBuilder.py | MIT | 2,820 | 247c505d40cc00d14f62c253e0f9ec8d25d61b20 | Python | py | |
import torch
import torch.nn.functional as F
from torch.nn import Linear
from torch_geometric.nn import SAGEConv, Set2Set
class Set2SetNet(torch.nn.Module):
def __init__(self, dataset, num_layers, hidden):
super().__init__()
self.conv1 = SAGEConv(dataset.num_features, hidden)
self.convs = ... | benchmark/kernel/set2set.py | MIT | 1,325 | 24950ec1decebf59dee2170ca29b73567592e5bc | Python | py | |
import torch
class TestMaskedConv2d(object):
def test_masked_conv2d(self):
if not torch.cuda.is_available():
return
from mmcv.op import MaskedConv2d
input = torch.randn(1, 3, 16, 16, requires_grad=True, device='cuda')
mask = torch.randn(1, 16, 16, requires_grad=True, d... | tests/test_op/test_masked_conv2d.py | Apache-2.0 | 447 | b21e3a034b4fb86ce04928e3872e86e62c001609 | Python | py | |
from collections import defaultdict
import inspect
import json
import os
import random
import torch
import transformers
from transformers import BatchEncoding
import ecco
import numpy as np
from IPython import display as d
from torch.nn import functional as F
from ecco.attribution import compute_primary_attributions_s... | src/ecco/lm.py | BSD-3-Clause | 34,970 | ffa9c159d5f3ae951e71c1fc630f68aebefb6eac | Python | py | |
#!/usr/bin/env python
import torch
import torch.nn as nn
import torch.nn.functional as F
from utils import Variable
class MultiGRU(nn.Module):
""" Implements a three layer GRU cell including an embedding layer
and an output linear layer back to the size of the vocabulary"""
def __init__(self, voc_si... | model.py | MIT | 4,773 | 3a102637908055f4aa95bb05a70eddecb0ed126e | Python | py | |
import time
import os
from PIL import Image, ImageOps
import pickle
from argparse import ArgumentParser
import torch
import torch.nn as nn
import yaml
from box import Box
import torchvision
from torchvision.models.detection.faster_rcnn import FastRCNNPredictor
from mask_utils import pad_image, get_transform
class Mas... | maskModel.py | MIT | 3,566 | 5f690e07afeac5b4f51904cf93dc469b634366dc | Python | py | |
# TODO merge naive and weighted loss.
import torch
import torch.nn.functional as F
def weighted_nll_loss(pred, label, weight, avg_factor=None):
if avg_factor is None:
avg_factor = max(torch.sum(weight > 0).float().item(), 1.)
raw = F.nll_loss(pred, label, reduction='none')
return torch.sum(raw * w... | mmdet/core/loss/losses.py | Apache-2.0 | 3,743 | 1e32fca5606bd686bcd5c9ddea114971b77bed61 | Python | py | |
from collections import OrderedDict
from itertools import product
import torch
from torchvision import models
import unittest
def get_available_classification_models():
# TODO add a registration mechanism to torchvision.models
return [k for k, v in models.__dict__.items() if callable(v) and k[0].lower() == k[... | test/test_models.py | BSD-3-Clause | 4,036 | 3a103c7149819cc734926a6895f2cb172d8c381f | Python | py | |
from __future__ import division
from __future__ import print_function
import os
import glob
import time
import random
import argparse
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torch.autograd import Variable
from utils import load_data, accur... | train.py | MIT | 5,289 | 3a106271acdc2096bc2c13d0add272220e4a625b | Python | py | |
from collections import defaultdict
from typing import List, Optional, Tuple, Union
import scipy.sparse
import torch
from torch import Tensor
from torch.utils.dlpack import from_dlpack, to_dlpack
import torch_geometric.data
from .num_nodes import maybe_num_nodes
def to_scipy_sparse_matrix(edge_index, edge_attr=Non... | torch_geometric/utils/convert.py | MIT | 9,303 | 2484e0b57ad993417085e2cb79e15ed282f6fe6b | Python | py | |
# pylint: disable=invalid-name,missing-class-docstring,no-member,missing-function-docstring.c-extension-no-member,too-many-locals,line-too-long,no-else-raise,too-many-arguments,no-self-use,too-many-statements,stop-iteration-return,import-outside-toplevel
'''script for detecting chars and extracting words'''
import typi... | keras_ocr/detection.py | MIT | 33,701 | d7a252efa9f32d65a32db16d76c25450be0c910e | Python | py | |
import torch
import time
import os
import argparse
from typing import Dict, List
from collections import defaultdict
from tkge.task.task import Task
from tkge.data.dataset import DatasetProcessor, SplitDataset
from tkge.train.sampling import NegativeSampler, NonNegativeSampler
from tkge.train.regularization import R... | tkge/task/trainer.py | MIT,Unlicense | 13,757 | 3a109e490f86a28f545b867235b4d85cb6c71407 | Python | py | |
from distutils.version import LooseVersion
import pytest
import torch
from espnet2.enh.encoder.stft_encoder import STFTEncoder
from espnet2.enh.layers.dnn_beamformer import BEAMFORMER_TYPES
from espnet2.enh.separator.neural_beamformer import NeuralBeamformer
is_torch_1_9_plus = LooseVersion(torch.__version__) >= Loo... | test/espnet2/enh/separator/test_beamformer.py | Apache-2.0 | 10,202 | 3a10c7a964398a24e69420d6355fe677cce4f03e | Python | py | |
from collections import OrderedDict
import pickle
import pytoda
import torch
import torch.nn as nn
from pytoda.smiles.transforms import AugmentTensor
from ..utils.hyperparams import ACTIVATION_FN_FACTORY, LOSS_FN_FACTORY
from ..utils.interpret import monte_carlo_dropout, test_time_augmentation
from ..utils.layers imp... | paccmann_predictor/models/bimodal_mca.py | MIT | 23,009 | 3a10ca5cbd3791b7a79649b5850087e990261317 | Python | py | |
import cv2
import os
import torch
from torch.distributions.weibull import Weibull
from torch.distributions.transforms import AffineTransform
from torch.distributions.transformed_distribution import TransformedDistribution
from detectron2.utils.logger import setup_logger
setup_logger()
from detectron2.config import get... | visualise_detections.py | Apache-2.0 | 3,745 | 24ad7093446eafd61a61cb0268e39f0d5665f91f | Python | py | |
from typing import List
import torch
from torch import Tensor
def accuracy(output: Tensor, target: Tensor, ks=(1,)) -> List[Tensor]:
"""
Args:
output: Tensor of shape :math:`(N, C)`
target: Tensor of shape :math:`(N,)`
Returns:
Top-k accuracy for each k in ``ks``.
.. referen... | src/utils/torch_metrics.py | Apache-2.0 | 934 | 3a111c47d0adacc7d17b24c366f1738cfa448c4d | Python | py | |
import torch
import torch.nn.functional as F
from torch.optim import Adam
from torch.nn.utils import clip_grad_value_
import numpy as np
from torch.optim.lr_scheduler import CosineAnnealingLR
class noop_callback:
def scalar(*args, **kwargs):
pass
class MAML:
def __init__(self, model, num_updates, te... | build/lib/sigver/metalearning/maml_pytorch.py | BSD-3-Clause | 7,835 | 3a1137361a368a20013aedb8f76dc8b514868793 | Python | py | |
import pytest
from torch.optim import SGD as _SGD
from neuralpy.optimizer import SGD
# Possible values that are invalid
learning_rates = [-6, False, ""]
momentums = [-6, False, ""]
dampenings = ["asd", False, 3]
weight_decays = [-0.36, "asd", "", False]
nesteroves = [122, ""]
@pytest.mark.parametrize(
"learning_... | tests/neuralpy/optimizer/test_sgd.py | MIT | 3,129 | 7c903ecc6f06e8b3feafda1c5b719f642a590347 | Python | py | |
import torch
import pyro
import numpy as np
import matplotlib.pyplot as plt
pyro.set_rng_seed(101)
def normal_density_estimation(data, size=1):
loc = pyro.sample("loc", pyro.distributions.Normal(0.0, 1.0))
inverse_scale = pyro.sample("inverse_scale", pyro.distributions.Gamma(3.0, 2.0))
with pyro.plate("data_pla... | HW03/q4-1.py | MIT | 1,108 | 5e366cd904e9464882f8a0f40ea1abbd73312841 | Python | py | |
#!/usr/bin/env python3
import json
import logging
import os
import re
import sys
from dataclasses import dataclass, field
from typing import Any, Dict, List, Optional, Union
import librosa
import datasets
import numpy as np
import torch
from packaging import version
from torch import nn
from torch.nn im... | run_classifier.py | MIT | 17,551 | 5f5479d30e4101d50ed5cd363e44cc765b43671d | Python | py | |
"""
Save util taken from stable_baselines
used to serialize data (class parameters) of model classes
"""
import base64
import functools
import io
import json
import os
import pathlib
import pickle
import warnings
import zipfile
from typing import Any, Dict, Optional, Tuple, Union
import cloudpickle
import torch as th
... | stable_baselines3/common/save_util.py | MIT | 19,098 | 4b2f1d68b0431f0cda1e81dd8c2c2913344c4001 | Python | py | |
from __future__ import print_function
import os
import argparse
import torch
import pickle
import torch.nn as nn
import pandas as pd
from torch.utils.data import DataLoader
from torch.autograd import Variable
from torch.nn.utils.rnn import pack_padded_sequence
from preprocessing import preprocess
from decoder import De... | CNN_LSTM/train_decoder.py | MIT | 7,821 | e9697809002def8d1c7185b1439ed986872ecc42 | Python | py | |
import argparse
import os
import torch
import numpy as np
from attrdict import AttrDict
from dataset_processing.dataset_loader import data_loader
from utils.absolute import relative_to_abs
from models.vrnn.vrnn_model import VRNN
from PIL import Image, ImageDraw
import matplotlib.pyplot as plt
import seaborn as sns
impo... | visualization/plot_model.py | Apache-2.0 | 2,974 | 3a11b53a9fbec75ff38c3f9465c8e0c39d4ef8af | Python | py | |
import torch
from torch import nn, einsum
from einops import rearrange, repeat
class SinusoidalEmbeddings(nn.Module):
def __init__(self, dim, theta = 10000):
super().__init__()
inv_freq = 1. / (theta ** (torch.arange(0, dim, 2).float() / dim))
self.register_buffer('inv_freq', inv_freq)
... | en_transformer/rotary.py | MIT | 853 | 5e771806c7fb3ab5629fd64cb6e75a8ff6a94328 | Python | py | |
'''
This is a bunch of stuff to start a beam search using gen_model_train as a
baseline. I'll try to implement augmentation and structure_data as well.
I'll additionally try to see how feasible it is to do an extendable beam search,
where we remember certain vectors for later.
We'll additionally incorporate ensemblin... | src/gen_model_beam_search_lm.py | BSD-2-Clause | 33,266 | 5f7c2e362d80b0a90a6991b507a5f1f632a1fbc6 | Python | py | |
from tqdm import tqdm
import copy
import numpy as np
import scipy.sparse as sp
import scipy.sparse.linalg as slinalg
from sklearn.cluster import KMeans
import torch
import torch.nn.functional as F
from .base_trainer import BaseTrainer
class M3STrainer(BaseTrainer):
def __init__(self, args):
super(M3STra... | cogdl/trainers/m3s_trainer.py | MIT | 8,560 | 3a11d6e6411a69bb4797b50f41c30a4e0a0ffd94 | Python | py | |
# Copyright (c) 2021, Soohwan Kim. 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 la... | conformer/modules.py | Apache-2.0 | 2,487 | f93ae274ec8050b3411c9322d8b69cfdd02403d4 | Python | py | |
# coding=utf-8
# 用这个来导入PyTorch包
import torch
"""
这一节介绍了tensor的广播broadcasting机制
"""
# 当两个形状不同的tensor进行按元素计算时可能会触发广播机制
# 广播会适当复制元素让两个tensor的形状相同然后再计算
# 两个 Tensors 只有在下列情况都符合下才能进行 broadcasting 操作:
# 1. 每个 tensor 至少有一维
# 2. 遍历所有的维度,从尾部维度开始,每个对应的维度大小要么相同,要么其中一个是1,要么其中一个不存在
# arange函数会得到[i,j)的排列
x = torch.arange(1, 61).vi... | Chapter2/Chapter2_2_3.py | BSD-2-Clause | 653 | 705c141d8078c44c866cb3a6120474ccc1dd16c8 | Python | py | |
import numpy as np
from PIL import Image
import os
import json
import gdown
import cv2
import torch
from .nets import PNet, RNet, ONet
from .stage_one import first_stage
from .stage_two import get_image_boxes
from .utils.visualize import show_boxes
from .utils.utils import nms, convert_to_square, calibrate_boxes
__P... | pyvision/misc/mtcnn/model.py | BSD-3-Clause | 7,391 | 427b8b7f19b036e77de51bbf76904f5ec9eecfb9 | Python | py | |
"""
loss_factory.py
returns various net models to be used
"""
import torch.nn
def loss_factory(loss_name, loss_params = None):
"""
returns a loss function to be used in training. we return None if we are unable to create
the requested loss
"""
if loss_name == 'NLL':
los... | multimodal_affinities/font_classifier/loss_factory.py | Apache-2.0 | 525 | 3af8b351c1149267d899e27ac95c2a54a8247e1f | Python | py | |
import torch
import functools
from torch import Tensor
from typing import Union
class fix_random_seed_ctx:
def __init__(self, seed: Union[Tensor, int]) -> None:
super().__init__()
self._seed = int(seed)
def __enter__(self):
self._prev_seed = torch.random.get_rng_state()
def __exi... | rising/random/utils.py | MIT | 620 | 3a1247c3516d530756d2ca5776738baa4386dcc1 | Python | py | |
import torch
import torchvision
import torchvision.transforms as transforms
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from model import AlexNet
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
# 将数据转换成PyTorch的tensor格式
transform = transforms.Compose(
[... | model/cifar10_alexnet/alexnet.py | Apache-2.0 | 2,100 | 3a124b26e6b898f055247002c00963a8bb7c7111 | Python | py | |
__author__ = "Max Dippel, Michael Burkart and Matthias Urban"
__version__ = "0.0.1"
__license__ = "BSD"
import torch
import logging
import scipy.sparse
import numpy as np
import pandas as pd
import signal
import time
import math
from sklearn.model_selection import StratifiedKFold
from autoPyTorch.pipeline.base.sub_pi... | autoPyTorch/pipeline/nodes/cross_validation.py | BSD-3-Clause | 9,370 | f9d0a923c8eeb26eb90765198b16a20a3d3c41f2 | Python | py | |
import math
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Function
from torch.autograd.function import once_differentiable
from torch.nn.modules.utils import _pair, _single
from mmdet.utils import print_log
try:
from . import deform_conv_cuda
except ImportError:
... | mmdet/ops/dcn/deform_conv.py | Apache-2.0 | 17,632 | 3a125bf61ad5953729499fc3df3f1aa0f524915c | Python | py | |
import os.path as osp
import json, pickle
import sys
from math import sqrt
from itertools import product
import torch
from numpy import random
import numpy as np
max_image_size = 550
augment_idx = 0
dump_file = '../weights/bboxes_aug.pkl'
box_file = '../weights/bboxes.pkl'
def augment_boxes(bboxes):
bboxes_rel = ... | scripts/augment_bbox.py | MIT | 3,984 | 80159b56b490d21a2b71f20053c0ec6b94b49ce3 | Python | py | |
# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appli... | nemo/collections/nlp/models/language_modeling/bert_lm_model.py | Apache-2.0 | 11,191 | 24f4fae8524a0678363c3cff08f1a0c3f135c45f | Python | py | |
#!/usr/bin/env python
import argparse
import importlib
import os
import torch
import data
import metrics
from mylib import misc, torch_utils
from model import StyleAwareDiscriminator
from model.augmentation import SimpleTransform
def parse_args():
parser = argparse.ArgumentParser()
for k, v ... | metrics/__main__.py | MIT | 2,845 | 5fca9f75b8bf597857e0241ac68b92838a7a6a45 | Python | py | |
from __future__ import division
import os
# os.environ['CUDA_VISIBLE_DEVICES'] = "2, 3"
import argparse
import copy
import mmcv
import time
import torch
import warnings
from mmcv import Config, DictAction
from mmcv.runner import get_dist_info, init_dist
from os import path as osp
from mmdet import __version__ as mmde... | tools/train.py | Apache-2.0 | 8,542 | 3a1295e7251ea4fc97c1f66d9f6dcba9f03396e5 | Python | py | |
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
# This script reuses some code from
# https://github.com/huggingface/transformers
import logging
import os
import pathlib
import sys
from datetime import datetime
import numpy as np
import torch
import torch.nn.functional ... | mtdnn/modeling_mtdnn.py | MIT | 31,097 | 802a60ff3c499f98b2e82c8f400913809c6b60c0 | Python | py | |
import torch
import torch.nn as nn
from torch.autograd import Variable
import numpy as np
def get_rnn(rnn_type, ninputs, nhid, nlayers, dropout=0, bidirectional=False):
if rnn_type in ['LSTM', 'GRU']:
return getattr(nn, rnn_type)(ninputs, nhid, nlayers, dropout=dropout,
... | model.py | Apache-2.0 | 14,396 | ff65c5a8983c2a51ac2c34db532792db6276e80b | Python | py | |
import os
import sys
sys.path.insert(0, os.getcwd())
import torch
from comvex.perceiver import Perceiver
if __name__ == "__main__":
perceiver = Perceiver(
data_shape=[1, 224, 224],
cross_heads=1,
num_latent_tokens=1024,
dim=512,
heads=16,
layers_indice=[0] + [1... | examples/Perceiver/demo.py | Apache-2.0 | 773 | 5e3498d028b990e6f8d153e75258ff15f097fc6d | Python | py | |
import dataclasses
from abc import ABC, abstractmethod
from typing import Generic, Iterable, Optional, Tuple, TypeVar
import torch
from torch import Tensor, nn
from ..prelude import Index, Self
from ..utils import Device
from .init import Initializer, lstm_bias
class RnnState(ABC):
@abstractmethod
def __get... | rainy/net/recurrent.py | Apache-2.0 | 7,557 | 3a12c1e52fa7f4fa5fa648fda094f773cd7cc1f5 | Python | py | |
"""
coding=utf-8
Copyright 2018, Antonio Mendoza Hao Tan, Mohit Bansal
Adapted From Facebook Inc, Detectron2 && Huggingface Co.
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... | build/lib/vltk/modeling/frcnn.py | Apache-2.0 | 77,019 | ff7acac205b4c6e08c3db6d52c4646140d0f11e3 | Python | py | |
from __future__ import print_function, division
import torch.nn as nn
import torch.nn.functional as F
import torch.utils.data
import torch
class conv_block(nn.Module):
"""
Convolution Block
"""
def __init__(self, in_ch, out_ch):
super(conv_block, self).__init__()
self.conv = ... | Models.py | MIT | 25,308 | 3a12f752729910f67905213c7b75fe6f7f125902 | Python | py | |
import numpy as np
import random
from collections import namedtuple, deque
from model import QNetwork
import torch
import torch.nn.functional as F
import torch.optim as optim
BUFFER_SIZE = int(1e5) # replay buffer size
BATCH_SIZE = 64 # minibatch size
GAMMA = 0.99 # discount factor
TAU = 1e-3 ... | dqn/exercise/dqn_agent.py | MIT | 6,170 | 3a13014218a010573368f3355d2f771946540015 | Python | py | |
import os
import csv
import enum
from torch.utils.data import dataloader
import json
from transformers.configuration_auto import AutoConfig
from utils.multiple_choices import MultipleChoiceDataset
from transformers import AutoTokenizer, AutoModelForMultipleChoice, WEIGHTS_NAME, RobertaForMultipleChoice
import torch
imp... | get_acc.py | MIT | 6,316 | 3a1301a572ade55c539f0ecee3371c2cf3f4058a | Python | py | |
# DO NOT alter/distruct/free input object !
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
import six
def make_np(x, modality=None):
if isinstance(x, np.ndarray):
return prepare_numpy(x, modality)
if isinstance(x, six.st... | tensorboardX/x2num.py | MIT | 3,955 | e9178221b5ff9acda6a26001f01d705b0774f514 | Python | py | |
#################################################################################
# Copyright (c) 2018-2021, Texas Instruments Incorporated - http://www.ti.com
# All Rights Reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditio... | torchvision/edgeailite/xnn/utils/weights_utils.py | BSD-3-Clause | 3,100 | 28ec7f08b0ef63749cdda909a0cfb1bf3e7ebb8b | Python | py | |
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import time, random, sys
import sklearn.metrics
from sklearn.model_selection import KFold
import torch
import torch.nn as nn
import torch.backends.cudnn as cudnn
import torch.optim as optim
from torch.utils.data import DataLoader
sys.path.append('... | src/train_model4.py | MIT | 8,516 | 3a1320129c3fcdfb724cc0f238e3f9303413d874 | Python | py | |
from __future__ import division, absolute_import
import torch.utils.model_zoo as model_zoo
from torch import nn
from torch.nn import functional as F
__all__ = ['mobilenetv2_x1_0', 'mobilenetv2_x1_4']
model_urls = {
# 1.0: top-1 71.3
'mobilenetv2_x1_0':
'https://mega.nz/#!NKp2wAIA!1NH1pbNzY_M2hVk_hdsxNM1NU... | torchreid/models/mobilenetv2.py | MIT | 8,387 | 3a132517d5e3f29bcf1227ac33dd9da9f8aba5ff | Python | py | |
#Code for training the BARZ network
import torch
import torch.backends.cudnn as cudnn
import torchvision.transforms as transforms
import torchvision.datasets as datasets
import torch.nn as nn
import ResNetBARZ
import time
import os
#Train the BARZ network from scratch
def TrainBARZNetwork(percentBiasPixel... | BarrierZoneTrainer/BarrierZoneTrainer/TrainingMethods.py | BSD-3-Clause | 7,445 | 1ea983920d97853a7469d742894574c6c6af9134 | Python | py | |
"""
This file is based on the code from https://github.com/pytorch/vision/blob/master/torchvision/datasets/folder.py.
"""
import pkg_resources
from torchvision.datasets.vision import VisionDataset
import torch
import torch.utils.data as data
import torchvision.transforms as transforms
from PIL import Image
import o... | robustbench/loaders.py | Apache-2.0 | 7,649 | f9f13d512e476bfd6ddd9d23ef014defa26306e4 | Python | py | |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Copyright 2019 Shigeki Karita
# Apache 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
"""Unility funcitons for Transformer."""
import torch
def add_sos_eos(ys_pad, sos, eos, ignore_id, max_len=None):
"""Add <sos> and <eos> labels.
:param torch.Tensor ys... | espnet/nets/pytorch_backend/transformer/add_sos_eos.py | BSD-3-Clause | 989 | 3a136463b71a14e9c2f971091e7dbca231e38233 | Python | py | |
from typing import Any, Union, Optional, List
import torch
from pytorch_lightning.accelerators.accelerator import Accelerator
from pytorch_lightning.plugins.training_type.training_type_plugin import TrainingTypePlugin
from pytorch_lightning.trainer.connectors.accelerator_connector import AcceleratorConnector
from pyto... | nni/retiarii/evaluator/pytorch/cgo/accelerator.py | MIT | 4,429 | 3a1364bd75348796c38342ce29b0a97839001998 | Python | py | |
#!/usr/bin/env python
from __future__ import division
from builtins import bytes
import os
import argparse
import math
import codecs
import torch
from table.Translator import Translator
import table.IO
import opts
from itertools import takewhile, count
try:
from itertools import zip_longest
except ImportError:
... | src/evaluate_question.py | MIT | 2,227 | 10f4e69b57a34b3b321447a9c6b2c0815a583829 | Python | py | |
import copy
# import random
import torch
import utils
import numpy as np
from model import Network
class ReplayBuffer(object):
def __init__(self, max_size, input_shape, n_actions) -> None:
"""Class to store agent's experience"""
self.max_size = max_size
self.memory_count = 0
# Exp... | src/agent.py | Unlicense | 6,329 | cc26821c828593d0136ceb1ccb1aebca721eee6a | Python | py | |
#!/usr/bin/env python3
# Copyright 2004-present Facebook. All Rights Reserved.
import logging
import matplotlib.pyplot as plt
import numpy as np
import os
import torch
import deep_sdf
import deep_sdf.workspace as ws
def running_mean(x, N):
cumsum = np.cumsum(np.insert(x, 0, 0))
return (cumsum[N:] - cumsum[:-... | plot_log.py | MIT | 2,974 | 3a137ba4b7632fe7c591ae24e1333a19441a0689 | Python | py | |
import pathlib
from typing import Any, Dict, List, Optional, Tuple, BinaryIO, Union
from torchdata.datapipes.iter import IterDataPipe, Mapper, Filter, IterKeyZipper, Demultiplexer, JsonParser, UnBatcher
from torchvision.prototype.datasets.utils import Dataset, HttpResource, OnlineResource
from torchvision.prototype.da... | torchvision/prototype/datasets/_builtin/clevr.py | BSD-3-Clause | 3,530 | 3a139787c6fb5b006bd092c18ea2126eb840f3e3 | Python | py | |
# -------------------------------------------
# import
# -------------------------------------------
import os
import sys
import argparse
import json
import torch
import torch.nn as nn
import torch.optim as optim
from torch.utils.data import DataLoader
from dataset import SemSegDataset
from models import UNet
from tr... | train.py | MIT | 2,798 | 3a139bfd0810693c9fd6466622df828eb5833803 | Python | py | |
from collections import defaultdict
import math
import os
import sys
import time
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
import tqdm
from numpy import random
from torch.nn.parameter import Parameter
import dgl
import dgl.function as fn
from utils import *
def get_graph(... | src/main.py | MIT | 12,838 | 45ea75bc7d4c3b08d2464eb7bd6b4be49e778669 | Python | py | |
import sys
import pickle
from collections import Counter
import numpy as np
import torch
from torch import nn
from torch import optim
from torch.utils.data import DataLoader
from tqdm import tqdm
from dataset import CLEVR, collate_data, transform
from model import MACNetwork
batch_size = 64
n_epoch = 20
dim = 512
d... | train.py | MIT | 3,463 | d77509ac8d90e7d94fdfb3e9d2ea960b948d0f79 | Python | py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.