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 |
|---|---|---|---|---|---|---|---|
from __future__ import division
from models import *
from utils.logger import *
from utils.utils import *
from utils.datasets import *
from utils.parse_config import *
from test import evaluate
from tqdm import tqdm
from terminaltables import AsciiTable
import os
import sys
import time
import datetime
import argpars... | Baseline_yolov3/train.py | MIT | 6,962 | 3a6159a05ea4a8a4267c3fac97d94ebf9d35da1b | Python | py | |
import collections
import os
import subprocess
import torch
from mlperf_logging import mllog
from mlperf_logging.mllog import constants
mllogger = mllog.get_mllogger()
def log_start(*args, **kwargs):
_log_print(mllogger.start, *args, **kwargs)
def log_end(*args, **kwargs):
_log_print(mllogger.end, *args... | Azure/benchmarks/bert/implementations/pytorch/mlperf_logger.py | Apache-2.0 | 2,165 | 3a6161f70a9837c58397db2c2f8ac2dec5a0f31c | Python | py | |
import numpy as np
import torch
import mxnet as mx
from PIL import Image
import cv2
from torch.utils.data import Dataset
import os
from collections import defaultdict
import numbers
class ImageDataset(Dataset):
def __init__(self, root_dir, transform):
super(ImageDataset, self).__init__()
self.trans... | dataset/datasets.py | MIT | 5,695 | 70473ef5369cf01b91ca79e7b913f6527715e132 | Python | py | |
# ------------------------------------------------------------------------
# Copyright (c) Hitachi, Ltd. All Rights Reserved.
# Licensed under the Apache License, Version 2.0 [see LICENSE for details]
# ------------------------------------------------------------------------
# Modified from DETR (https://github.com/fac... | models/detr.py | Apache-2.0 | 21,355 | 705502a8df2fda6a87a57eb2d355bd54c367c926 | Python | py | |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import os
import sys
root_path = "/".join(os.path.realpath(__file__).split("/")[:-2])
if root_path not in sys.path:
sys.path.insert(0, root_path)
import csv
import logging
import argparse
import random
import numpy as np
from tqdm import tqdm
from torch.utils.da... | dataset_readers/bert_data_utils.py | MIT | 12,424 | 45a14cb16403f245172f0172a52c08ad7ed9e987 | Python | py | |
from typing import Dict, Generic, List, TypeVar
import torch
from allennlp.data.vocabulary import Vocabulary
DataArray = TypeVar("DataArray", torch.Tensor, Dict[str, torch.Tensor]) # pylint: disable=invalid-name
class Field(Generic[DataArray]):
"""
A ``Field`` is some piece of a data instance that ends up... | allennlp/data/fields/field.py | Apache-2.0 | 6,464 | 3a617a3c2955ee266c7c4301bc2b732277f83e73 | Python | py | |
import torch
import torchvision
from torch.optim import Adam
_opt_dict = {"Adam": Adam}
def get_opt(name):
return _opt_dict[name]
def config_to_str(config):
attrs = vars(config)
string_val = "Config: -----\n"
string_val += "\n".join("%s: %s" % item for item in list(attrs.items()))
string_val +=... | src/utils/cluster/general.py | MIT | 1,587 | 3a6182301f67828d5dacb31b7f0aa6c0f74218ee | Python | py | |
import torch
from torch.utils.data import DataLoader
from alignments.aer import AERSufficientStatistics
from alignments.models import AlignmentVAE
from alignments.data import PAD_TOKEN, create_batch
from alignments.train_utils import alignment_summary
def create_model(hparams, vocab_src, vocab_tgt):
return Align... | alignments/alignmentvae_helper.py | MIT | 8,680 | 4b057ae34060affdc0a9d780e43d0c98556e0f40 | Python | py | |
"""
Training of WGAN-GP
"""
import torch
import torch.nn as nn
import torch.optim as optim
import torchvision
import torchvision.datasets as datasets
import torchvision.transforms as transforms
from torch.utils.data import DataLoader
from torch.utils.tensorboard import SummaryWriter
from utils_zp import gradient_penal... | ML/Pytorch/GANs/4. WGAN-GP/train_zp.py | MIT | 3,831 | 529ca9039a5badd8f8e727a45bfb6695f902ab9e | Python | py | |
import os
import numpy as np
import sys
import struct
from torch.utils.data import Dataset
def pixel2world(x, y, z, img_width, img_height, fx, fy):
w_x = (x - img_width / 2) * z / fx
w_y = (img_height / 2 - y) * z / fy
w_z = z
return w_x, w_y, w_z
def world2pixel(x, y, z, img_width, img_height, fx, ... | integral-pose/msra_hand.py | MIT | 7,204 | 3a61a940caa06038da669fdebea330db1978e961 | Python | py | |
import os
import torch
from setuptools import setup
from torch.utils.cpp_extension import BuildExtension, CUDAExtension
rootdir = os.path.dirname(os.path.realpath(__file__))
version = "0.1.2"
ext_modules = []
if torch.cuda.is_available():
ext = CUDAExtension(
"block_sparse_native",
[
... | setup.py | BSD-3-Clause | 1,783 | 4b7596effc207f2115ae853f5a599164fae8bd5e | Python | py | |
import torch
import torch.nn as nn
from hyperbox.mutables.spaces import OperationSpace
from hyperbox.networks.base_nas_network import BaseNASNetwork
from hyperbox.mutator import RandomMutator
class ToyDuplicateNet(BaseNASNetwork):
def __init__(self):
super().__init__()
self.op1 = OperationSpace(c... | tests/mutables/test_duplicate_mutables.py | MIT | 921 | 03faf01ad841bb31f2473c648505ad030da57c6f | Python | py | |
from easydict import EasyDict as edict
import torch
args = edict(
{
"model": "gpt2",
"dataset_path": "./data/personachat_self_original.json",
"dataset_cache": "./cache.tar.gz_GPT2Tokenizer",
"persona_cache": "cache/persona_cache",
"history_cache": "cache/history_cache",
... | models/config.py | MIT | 637 | 3a61c51d6bc252d053d4b0ea2d14468f97689b9b | Python | py | |
import torch
import torch.nn.functional as F
import argparse
import cv2
import numpy as np
from glob import glob
import matplotlib.pyplot as plt
num_classes = 2
img_height, img_width = 64, 64#572, 572
out_height, out_width = 64, 64#388, 388
GPU = False
torch.manual_seed(0)
class Mynet(torch.nn.Module):
def __... | Question_semaseg/answers/transposeconv_pytorch.py | MIT | 7,100 | 3a61cc18b79548b6961cb3fb8b72baf095d3fa0e | Python | py | |
from torch import nn
import torch
class GeneratorUNet(nn.Module):
def __init__(self):
super(GeneratorUNet, self).__init__()
# Convolution layers
nc = 3
ngf = 64
# input is (nc) x 256 x 256
self.conv1 = nn.Conv2d(nc, ngf, 4, 2, 1, bias=True)
... | CycleGAN/model/networks.py | MIT | 11,587 | 5e1dee99de76db36ba48233edc5c60960027376e | Python | py | |
import torch
import torch.nn as nn
class Metrics(nn.Module):
def __init__(self, threshold=0.5):
super(Metrics, self).__init__()
self.threshold = threshold
def forward(self, pred, true):
eps = 1e-10
pred_ = (pred > self.threshold).data.float()
true_ = (true > self.thres... | geometry_translation/models/metrics.py | MIT | 876 | 3a620716ff49e3ada83864b7a6429d2fb58ff023 | Python | py | |
#%%writefile end-end.py
import os
import cv2
import sys
import time
import collections
import torch
import argparse
import numpy as np
#import torch.nn as nn
#import torch.nn.functional as F
#import pytesseract
import params
import torchvision.transforms as transforms
from torch.autograd import Variable
from torch.uti... | end-end.py | Apache-2.0 | 6,294 | 3a6209d60085ab9cb1a332e17172924c25823382 | Python | py | |
from itertools import zip_longest
import convert_matlab73_hdf5
from os import listdir
from os.path import join
import torch
import h5py
import matplotlib.pyplot as plt
import numpy as np
def get_valid_ids_and_labels(trial_number, stimulus_id, stimulus_pos, trial_answer, debug=False):
valid_trial_ids = []
label... | src/eeg_dataset_utils.py | MIT | 4,880 | 3a6234a27160149f64ad7b347f0632645fc9dfb2 | Python | py | |
from numpy.lib.type_check import _nan_to_num_dispatcher
from flow.core.params import VehicleParams
import numpy as np
import torch
import os
import traci
from functools import partial
from tqdm import tqdm
from .a2c_ppo_acktr import utils
from .a2c_ppo_acktr.envs import make_vec_envs
import matplotlib.pyplot as plt
f... | train/myppo/evaluation.py | MIT | 23,644 | d77527ac717a7b497ea6b7b4ae3b1a6280039f06 | Python | py | |
import torch
import torch.nn as nn
from torch.autograd import Variable
import copy
from contextlib import contextmanager
import warnings
warnings.filterwarnings(action='ignore', category=UserWarning)
use_context_mans = int(torch.__version__[0]) * 100 + int(torch.__version__[2]) - \
(1 if 'a' in t... | reversible2/newrevblock.py | MIT | 11,135 | 1eacf3aca2382d756455afb767217611bd348e34 | Python | py | |
import datetime
import logging
from pathlib import Path
from typing import List, Tuple
import numpy as np
import torch
import torch.distributed as dist
from sklearn.metrics import confusion_matrix
from torch.utils.tensorboard import SummaryWriter
from fltk.nets.util.evaluation import calculate_class_precision, calcul... | fltk/client.py | BSD-2-Clause | 13,059 | f944582ea4079a1733b8b2987309a5616e656237 | Python | py | |
from torchvision import transforms
import torch.nn.functional
from torch.utils import cpp_extension
import numpy as np
import os
import sys
# Load external cpp files
def load_ext_cpp():
script_path = os.path.dirname(os.path.realpath(__file__))
flags = ['-O3']
sources = [
os.path.join(script_path... | src/GradientMap.py | MIT | 5,372 | 24c881a7f5263a38722ec7442588291eb1e67997 | Python | py | |
from itertools import filterfalse as ifilterfalse
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Variable
from torch.nn import BCELoss
class ABRLovaszLoss(nn.Module):
"""Lovasz loss for Alpha process"""
def __init__(self, ignore_index=None, only_present=True):... | losses/lorenz.py | Apache-2.0 | 16,284 | 3a625779870260dfedf9cddbbf356fec48af8d16 | Python | py | |
import numpy as np
import pytest
import torch
import torch.nn as nn
from mmdet.core import auto_fp16, force_fp32
from mmdet.core.fp16.utils import cast_tensor_type
def test_cast_tensor_type():
inputs = torch.FloatTensor([5.])
src_type = torch.float32
dst_type = torch.int32
outputs = cast... | tests/test_fp16.py | Apache-2.0 | 10,014 | d78e194348a58f24af30c1051a7c73a548268009 | 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 os
import time
from collections import defaultdict, deque
from typing import Any, Dict, List, Optional
import ra... | habitat_baselines/rl/ppo/ppo_trainer.py | MIT | 59,921 | e93f9d5ac2ea5a62474d8b6a65c9d4fba1d97416 | Python | py | |
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
def hard_pad2d(x, pad):
def pad_side(idx):
pad_len = max(pad - x.size(idx), 0)
return [0, pad_len]
padding = pad_side(3)
padding.extend(pad_side(2))
x = F.pad(x, padding)
return x[:, :, :pad, :pad... | vdpwi/model.py | Apache-2.0 | 7,129 | 3a62a0a0f29ebbca2c3afb05ba74313dce116b9b | Python | py | |
import unittest
import torch
import sys
sys.path.append("/content/drive/MyDrive/pytorch_Realtime_Multi-Person_Pose_Estimation/evaluate")
sys.path.append("/content/drive/MyDrive/pytorch_Realtime_Multi-Person_Pose_Estimation/evaluate/coco_eval.py")
sys.path.append("/content/drive/MyDrive/pytorch_Realtime_Multi-Person_Pos... | evaluate/evaluation.py | MIT | 1,905 | 24c2e2db2f2a59531aee8067ea030c7998c5f6e0 | Python | py | |
import torch
import numpy as np
import h5py
import os
import sys
sys.path.append(os.path.dirname(os.path.dirname(os.path.realpath(__file__))))
from scv2.dataset import decode_mp3, pad_or_truncate
from models.models_mae import AugmentMelSTFT
def get_mean_std(n_mel=128, sample_number=10000):
print('Start...')
h... | scv2/get_mean_std.py | Apache-2.0 | 2,323 | 10bb2b93c1bac79878322643472a20cb640b1c84 | Python | py | |
from __future__ import print_function
import codecs
import gzip
import os
import os.path
import numpy as np
import torch
import torch.utils.data as data
from PIL import Image
from .utils import download_url, makedir_exist_ok
class MNIST(data.Dataset):
"""`MNIST <http://yann.lecun.com/exdb/mnist/>`_ Dataset.
... | lib/mnist.py | Apache-2.0 | 13,681 | 3a62d7b9974af32c50138f5517d1e5b041093b0e | Python | py | |
import os
import math
import pickle
import random
import numpy as np
import torch
import cv2
import scipy.ndimage
####################
# Files & IO
####################
###################### get image path list ######################
IMG_EXTENSIONS = ['.jpg', '.JPG', '.jpeg', '.JPEG', '.png', '.PNG', '.ppm', '.PPM',... | codes/data/util.py | MIT | 15,268 | 1e6162586c5277bbf11a28010f82e8d8b3c28c9a | Python | py | |
'''Module for handling noise.
'''
import torch
import torch.distributions as tdist
_dist_dict = dict(
bernoulli=tdist.bernoulli.Bernoulli,
beta=tdist.beta.Beta,
binomial=tdist.binomial.Binomial,
categorical=tdist.categorical.Categorical,
cauchy=tdist.cauchy.Cauchy,
chi2=tdist.chi2.Chi2,
... | cortex/_lib/data/noise.py | BSD-3-Clause | 2,263 | 3a62e9323fdadfb0a5cf8a23d7467416d3196e9e | Python | py | |
import torch
import torch.nn as nn
import torch.optim as optim
import torch.optim.lr_scheduler as lr_scheduler
from torch.utils.data import DataLoader
import math, random, sys
import numpy as np
import argparse
from tqdm import tqdm
import rdkit
from rdkit import Chem
from poly_hgraph import *
lg = rdkit.RDLogger.lo... | polymers/reconstruct.py | MIT | 2,097 | 3a62f08e79cb940c69a4e80f77884b09f00ec908 | Python | py | |
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
from copy import deepcopy
from typing import Optional
import torch
import torch.nn as nn
from fvcore.nn.squeeze_excitation import SqueezeExcitation as SqueezeExcitationFVCore
from pytorchvideo.accelerator.efficient_blocks.efficient_block_base imp... | pytorchvideo/layers/accelerator/mobile_cpu/attention.py | Apache-2.0 | 4,399 | 3a6309e4a30e2f12dab03b94273d98ed17a2e888 | Python | py | |
# Copyright 2020-2022 OpenDR European Project
#
# 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 agree... | tests/sources/tools/perception/skeleton_based_action_recognition/test_stbln.py | Apache-2.0 | 10,041 | f95d01f570b14bbc8b31ed80a0010dca7d174031 | Python | py | |
import math
import os
import os.path
import time
import sys
import numpy as np
import scipy.misc
import cv2 as cv
import torch
import torch.nn as nn
import torch.nn.functional as F
import skimage
import imageio
from PIL import ImageFont, ImageDraw, Image
from console_progressbar import ProgressBar
import inference
f... | SuperresolutionNetwork/mainComparisonVideo3.py | MIT | 22,650 | 3a634ef8b42bc15a731cafb952b61fc2820d337f | Python | py | |
# model : ClipVinvlGpt
'''
origianl show_and_tell with improving abillity of each layer(ClipGpt) + meaningful features(Vinvl)
'''
import torch.nn as nn
from pytorchcv.model_provider import get_model as ptcv_get_model
from torch.nn.utils.weight_norm import weight_norm
import clip
clip_model, preprocess = clip.load(... | models/base_model_with_detection.py | MIT | 13,080 | 1054aff595fba47a4edb5153cbb0891086171d30 | Python | py | |
import torch
import torch.nn as nn
import numpy as np
import scipy.io as sio
class Block(nn.Module):
def __init__(self, in_ch, k):
super(Block, self).__init__()
self.H = nn.Sequential(
nn.BatchNorm2d(in_ch),
nn.ReLU(inplace=True),
nn.Conv2d(in_ch, k, 1... | Day 4/DenseNetV2.py | MIT | 5,207 | 3a63c72ed959d913290ef14e0266af7460cf453d | Python | py | |
import numpy as np
import os
import json
import torch
import matplotlib.pyplot as plt
# ----------------------- Plotting --------------------------------------- #
def plot_training_scores(scores, goal_score, window=100,
agent_name=None,
ylabel='Score'):
fig = p... | agent_utils.py | MIT | 7,768 | 4b0309b04089a6690ba33c208d05fa5a310b247b | Python | py | |
#!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
import collections
from typing import List, Optional
import torch
from pytext.config.field_config import WordFeatConfig
from pytext.data.tensorizers import Tensorizer
from pytext.data.utils import UNK
from pytext.fields impo... | pytext/models/embeddings/word_embedding.py | BSD-3-Clause | 5,770 | 3a64077aa5d5e20fe31459a3c78bf6a36ecd9f2e | Python | py | |
import sys
import os
import numpy as np
from matplotlib import pyplot as plt
from scipy.stats import pearsonr
import torch
from torch import nn
from torch.utils.checkpoint import checkpoint
import selene_sdk
from selene_sdk.samplers.dataloader import SamplerDataLoader
sys.path.append("..")
from selene_utils2 import... | train/train_h1esc_c.py | Apache-2.0 | 18,070 | 3a6417212792e50f5e884f5c85c17be5532d9674 | Python | py | |
import numpy as np
import pandas as pd
import pickle
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
import torchvision
from torchvision import datasets, transforms
from torch.autograd import Variable
import torch.utils.data as data
from sklearn.metrics import roc_auc_scor... | synthetic/LSTM11q_functions.py | MIT | 9,491 | 1e91090336b96c4cafc1eadf053283b163e429c8 | Python | py | |
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT license.
import os
import time
import math
import copy
import numpy as np
import torch
import torch.nn as nn
from nni.compression.torch.compressor import PrunerModuleWrapper
from .lib.utils import prGreen
from .. import AMCWeightMasker
# for pruning
def... | src/sdk/pynni/nni/compression/torch/pruning/amc/channel_pruning_env.py | MIT | 27,410 | fdd0694e1b152f44c6e05b2046fc09a871ded5d9 | Python | py | |
import cv2
import numpy as np
import torch
from pytorch_grad_cam.base_cam import BaseCAM
from pytorch_grad_cam.utils.svd_on_activations import get_2d_projection
# Like Eigen CAM: https://arxiv.org/abs/2008.00299
# But multiply the activations x gradients
class EigenGradCAM(BaseCAM):
def __init__(self, model, targe... | pytorch_grad_cam/eigen_grad_cam.py | MIT | 741 | 1e9bc8ee65746ed6cfb2fe6b5f19a01350aa3809 | Python | py | |
"""
This is meant to run all experiment models on every photo used for training and evaluation. The purpose of this is to compare which outcomes have been correctly classified to determine any potential underlying biases and have a better idea of the model's overall performance.
"""
import os
import torch
import... | public/model_utils.py | Apache-2.0 | 15,877 | 3a6483c907e1d3e7fb2576aa0126a53f990d2c98 | Python | py | |
"""
The main file to train P3GM and construct synthetic data.
"""
import argparse
import torch
import numpy as np
import pandas as pd
from p3gm import P3GM
from vae import VAE
import pathlib
filedir = pathlib.Path(__file__).resolve().parent
import my_util
import datetime
import json
import ml_task.exp_ml
parser = arg... | src/synthesize.py | MIT | 4,930 | e603200591a05d00d34214894f7a99e72712c38c | Python | py | |
#
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
#
from rlstructures import logging
from rlstructures.env_wrappers import GymEnv
from rlstructures.tools import weight_init
import torch.nn ... | tutorial/tutorial_reinforce/main_reinforce.py | MIT | 1,956 | 3a649f683b1c46c8ac7db15fd77f157c881afeee | Python | py | |
from __future__ import absolute_import, division, print_function
import math
import torch
def rinverse(M, sym=False):
"""Matrix inversion of rightmost dimensions (batched).
For 1, 2, and 3 dimensions this uses the formulae.
For larger matrices, it uses blockwise inversion to reduce to
smaller matri... | pyro/ops/linalg.py | MIT | 3,159 | 3a64a99253af3c8c9bd64280f74313c10705ed1a | Python | py | |
import os
from options.train_options import TrainOptions
from models import create_model
from util.visualizer import save_images
from util import html
import string
import torch
import torchvision
import torchvision.transforms as transforms
from data.image_folder import ImageFolder
from util import util
import nump... | test.py | MIT | 5,459 | 10242446b00d3c8b2634952eec50b8de49518d1b | Python | py | |
#!/usr/bin/env python3
import struct
import sys
import torch
import torch.nn as nn
import wav2letter._criterion as _C
def get_data_ptr_as_bytes(tensor):
return struct.pack("P", tensor.data_ptr())
def get_cuda_stream_as_bytes():
s = torch.cuda.current_stream().cuda_stream
return s.to_bytes(_C.sizeof_cu... | bindings/python/wav2letter/criterion_torch.py | BSD-3-Clause | 6,955 | 3a64cb67a7dad282b7f76f422ae1ea1abeebbd59 | Python | py | |
"""
BSD 3-Clause License
Copyright (c) 2018, NVIDIA Corporation
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of c... | tacotron2_model/utils.py | BSD-3-Clause | 2,303 | 28e82f3f872361771dec219b99a329e92117ecdf | Python | py | |
import torch
def random_split(data, validation_percent):
validation_points = int(validation_percent * len(data))
return torch.utils.data.random_split(
data, [validation_points, len(data) - validation_points]
)
| src/utils.py | MIT | 232 | cc2469a403959edd4a3b6fe0c40058fcaadb2df2 | Python | py | |
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT license.
import warnings
from contextlib import contextmanager
import hashlib
import os
import shutil
import tempfile
import torch
import gzip
import tarfile
import zipfile
from torchvision.datasets.folder import ImageFolder
ARCHIVE_META =... | scripts/imagenet.py | MIT | 11,459 | 347d3dc4532f4b01729c121caba947ccc62edf06 | Python | py | |
import torch.nn as nn
# Basic ConvNet with Pooling layer
def conv_block(in_channels, out_channels):
return nn.Sequential(
nn.Conv2d(in_channels, out_channels, 3, padding=1),
nn.BatchNorm2d(out_channels),
nn.ReLU(),
nn.MaxPool2d(2),
)
class ConvNet(nn.Module):
def __init__(... | examples/fewshot/networks/convnet.py | MIT | 734 | 3a64d4d5f4b52b478872e6a638e2d2fe66ddd936 | Python | py | |
#!/usr/bin/env python 3
# -*- coding: utf-8 -*-
#
# Copyright (c) 2020 PanXu, Inc. All Rights Reserved
#
"""
将模型输出转化成最终的label
Authors: PanXu
Date: 2020/07/05 10:20:00
"""
import torch
from typing import List, Tuple
from easytext.model import ModelOutputs
from easytext.data import LabelVocabulary
class ModelLabe... | easytext/label_decoder/model_label_decoder.py | MIT | 1,517 | 28b6ea17424ac741638046634e1467d4445bbb69 | Python | py | |
from __future__ import print_function
from __future__ import division
import os
import sys
import time
import datetime
import argparse
import os.path as osp
import numpy as np
import torch
import torch.nn as nn
import torch.backends.cudnn as cudnn
from torch.utils.data import DataLoader
from torch.optim import lr_sch... | test_vidreid_xent.py | MIT | 14,778 | 3a64fcfb83e11f326048d71b4479522dc0a80969 | Python | py | |
"""Main entry point for training a model.
- Parse the config and create objects.
- Load the necessary resources.
- Train the model, with periodic evaluation.
"""
import gzip
import json
import logging
import os
from os.path import dirname, realpath, join
import random
import numpy as np
from tqdm import tqdm
import t... | phrasenode/training_run.py | Apache-2.0 | 11,311 | 3a65169b5052140269a1357a6b42ee07e21c39ce | Python | py | |
from functools import partial
from pathlib import Path
import numpy as np
import torch
from torch.utils.data import DataLoader
from tqdm import tqdm
from synthesizer.models.tacotron.hparams import hparams_debug_string
from synthesizer.models.tacotron.tacotron import Tacotron
from synthesizer.models.tacotron.synthesiz... | synthesizer/models/tacotron/synthesize.py | MIT | 3,813 | 426357e439991ecbd0e8500a9950554d2e0d9253 | Python | py | |
#!/usr/bin/env python3
# Copyright 2021 Xiaomi Corp. (authors: 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... | egs/librispeech/ASR/transducer_stateless/test_decoder.py | Apache-2.0 | 1,518 | 3a653c1b7b81a3d7dc316ac30d69593663564c61 | Python | py | |
import logging
import click
import flash
import mlflow
import torch
import torchmetrics
from flash.text import TextClassificationData, TextClassifier
logging.basicConfig(level=logging.INFO, format="%(asctime)-15s %(message)s")
logger = logging.getLogger()
@click.command(help="This program finetunes a deep learning ... | chapter04/pipeline/fine_tuning_model.py | MIT | 1,996 | a93610f2e7d81d40bf030ccb1526b3a82185d744 | Python | py | |
"""
`파이토치(PyTorch) 기본 익히기 <intro.html>`_ ||
`빠른 시작 <quickstart_tutorial.html>`_ ||
`텐서(Tensor) <tensorqs_tutorial.html>`_ ||
`Dataset과 Dataloader <data_tutorial.html>`_ ||
`변형(Transform) <transforms_tutorial.html>`_ ||
`신경망 모델 구성하기 <buildmodel_tutorial.html>`_ ||
`Autograd <autogradqs_tutorial.html>`_ ||
`최적화(Optimizat... | docs/_downloads/53212b54b9761368eb3dcf3494b14182/saveloadrun_tutorial.py | BSD-3-Clause | 2,268 | e94c0119d610ae6d35822d89cf72cddde6325e36 | 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/accelerators/tpu_backend.py | Apache-2.0 | 7,519 | 1e807cd6fa831bd344f8e7e8622d54575668fc66 | Python | py | |
import torch
import torch.nn as nn
import torch.nn.functional as F
from ..module.nn import CNN
from ..module.pool import MaxPool
from .base_encoder import BaseEncoder
from nltk import word_tokenize
class PCNNEncoder(BaseEncoder):
def __init__(self,
token2id,
max_length=128,
... | opennre/encoder/pcnn_encoder.py | MIT | 6,986 | 12d19d5e8f442ce16363ed340e5944c9cf9423ee | Python | py | |
import torch
import numpy as np
import json
def dump_tensor_dict(msg, tensor_dict):
"""
dump dict with tensors in. doesnt print the entirety of every tensor...
"""
print(msg)
for k, v in tensor_dict.items():
if isinstance(v, torch.Tensor):
if (v != 0).long().sum().item() * 3 < ... | ulfs/debug.py | MIT | 770 | 3a6594ee40671c8977ae2fd10d7068da1770b803 | Python | py | |
# -*- coding: utf-8 -*-
# @Author : William
# @Project : TextGAN-william
# @FileName : seqgan_instructor.py
# @Time : Created at 2019-06-05
# @Blog : http://zhiweil.ml/
# @Description :
# Copyrights (C) 2018. All Rights Reserved.
import torch
import torch.optim as optim
import config ... | instructor/real_data/seqgan_instructor.py | MIT | 5,834 | 128a922485abd2708a31344da48cbf33a3521f2a | Python | py | |
import torch
from torch import nn
import torch.nn.functional as F
import torch.optim as optim
import numpy as np
from dql.helper import Transition
from dql.helper import get_latest_model_path
# from torch.utils.tensorboard import SummaryWriter
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
class... | src/dql/model.py | MIT | 4,494 | 3a65a296bdb8cf56917cd9f74a54c43b5fd9cc12 | Python | py | |
import torch
import torch.nn as nn
import torch.nn.init as init
__all__ = ['Resnet_dropout']
def init_params(net):
'''Init layer parameters.'''
for m in net.modules():
if isinstance(m, nn.Conv2d):
init.kaiming_normal_(m.weight, mode='fan_out')
#print(m.bias)
if m.bia... | SVHN/models/resnet_dropout.py | Apache-2.0 | 3,101 | d7f29daa497442565b44bdb2f6b0c15d8a47d719 | Python | py | |
"""Utility functions for building models"""
import torch
import torch.nn as nn
def make_mlp(input_size, sizes,
hidden_activation='ReLU',
output_activation='ReLU',
layer_norm=False):
"""Construct an MLP with specified fully-connected layers."""
hidden_activation = getatt... | GraphLearning/src/notebooks/model_utils.py | BSD-3-Clause-LBNL | 1,000 | 3a65c42a4969a0d0995afd305bcc9500236f350b | Python | py | |
"""
Copyright (c) 2019-2020 Intel Corporation
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in w... | tests/torch/test_backward_compat.py | Apache-2.0 | 7,907 | 3a66000a3b389303877c611837581e5c974446e9 | Python | py | |
import torch
class GradEstimator:
"""
Contains three methods for gradient estimation, each instantiated GradEstimator object uses one of them.
For math, see https://arxiv.org/pdf/1804.02395.pdf.
The first method is the 'vanilla' gradient estimator, based on a standard REINFORCE score function estimato... | scripts/grad_estimators.py | MIT | 5,132 | a932132a7b5cdb5f07bc8e2e95e3d8a1b404d092 | Python | py | |
"""
This file is adapted from following files in openai/baselines.
common/segment_tree.py
deepq/replay_buffer.py
baselines/acer/buffer.py
"""
import operator
import random
import numpy as np
import torch
class SegmentTree(object):
def __init__(self, capacity, operation, neutral_element):
"""Build a Segme... | src/common/replay_buffer.py | MIT | 9,773 | 3a66072d892137f9796f43947f6f8fbf03f06396 | Python | py | |
import numpy as np
import time
import os
import argparse
from sklearn import preprocessing
import matplotlib.pyplot as plt
import math
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.utils.data as data
import torch.optim as optim
from torch.autograd import Variable
import _pickle as cP... | pytorch/denoise_impaint_complete.py | MIT | 10,568 | 1e5262bd6398f0d82a1e83c93562d79d510a015f | Python | py | |
import os
import matplotlib.pyplot as plt
import torch
import src.envs.core as ising_env
from experiments.utils import test_network, load_graph_set
from src.envs.utils import (SingleGraphGenerator,
RewardSignal, ExtraAction,
OptimisationTarget, SpinBasis,
... | experiments/ER_40spin/test/test_eco.py | MIT | 4,610 | 45f42369805ff2c09f1aadd3e6bd805b75b41ec2 | Python | py | |
import itertools
from unittest.mock import patch
from torchaudio._internal import module_utils as _mod_utils
from torchaudio.backend import _soundfile_backend as soundfile_backend
from parameterized import parameterized
from torchaudio_unittest.common_utils import (
TempDirMixin,
PytorchTestCase,
skipIfNo... | test/torchaudio_unittest/soundfile_backend/save_test.py | BSD-2-Clause | 8,098 | a99c69b0c86b7c8176d30444bab0e0e3694f22f8 | Python | py | |
import os
import time
import sys
import random
import torch
import traceback
import dlib
# What do we define as a parameter what not.
from configs import g_conf, set_type_of_process, merge_with_yaml
from network import CoILModel, Loss
from input import CoILDataset, Augmenter
from logger import coil_logger
from coilu... | coil_core/validate.py | MIT | 10,338 | 3a6644d1f641958ef4846b569ac4c9d5fc58a4ac | Python | py | |
import torch
import torch.nn as nn
from layers.linear_bayesian_layer import BayesianLinear
from blitz.utils import variational_estimator
##### Bayesian version #####
@variational_estimator
class BERT_BAYES_SPC(nn.Module):
def __init__(self, bert, opt):
super(BERT_BAYES_SPC, self).__init__()
self.b... | models/bert_bayes_spc.py | MIT | 1,026 | 3a664c9a35d30db0f5b2424483febbc7165513f8 | Python | py | |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import torch.utils.data as data
import torchvision.transforms as transforms
from PIL import Image
import PIL
import os
import os.path
import pickle
import random
import ... | code/datasets.py | MIT | 12,078 | 7c7af7c2de6c78052cd1a746ee2ddb0849e36d51 | Python | py | |
import numpy as np
import torch
def SILog(yhat, y, L = 1):
'''
yhat: prediction
y: ground truth
L: λ in the paper, [0,1]. L=0 gives elementwise L2 loss,
L=1 gives scale-invariant loss.
https://arxiv.org/pdf/1406.2283.pdf
'''
idx = ~torch.isnan(y)
di = torch.log(yhat[idx] + 1e-10... | data/metrics.py | MIT | 5,050 | 3a665488f05261c6e67f5af6af33282a9904e9f4 | Python | py | |
import torch
from .base_model import BaseModel
from . import networks
class Pix2PixModel(BaseModel):
""" This class implements the pix2pix model, for learning a mapping from input images to output images given paired data.
The model training requires '--dataset_mode aligned' dataset.
By default, it uses ... | models/pix2pix_model.py | BSD-3-Clause | 6,591 | dfdb18a62881cb1e6589ccaa54f84f8ec1035721 | Python | py | |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
from typing import List, Dict, Any, Optional
import io, copy, random
import pickle
from collections import defaultdict
from tqdm import tqdm
import numpy as np
from torch.utils.data import Dataset
from dataset.contextualized_embeddings import BERTEmbeddingsDataset
from dat... | dataset/gloss_embeddings.py | Apache-2.0 | 13,950 | 3a66b0b718aba860ac88f1ec7ac7be9788cbc872 | Python | py | |
#!/usr/bin/env python3
# @brief: Get a 3D point cloud from a given range image projection
# @author Benedikt Mersch [mersch@igg.uni-bonn.de]
import torch
import torch.nn as nn
import numpy as np
class projection:
"""Projection class for getting a 3D point cloud from range images"""
def __init__(self... | pcf/utils/projection.py | MIT | 3,156 | 428a2a25d4ad3af545f713ae4e24e587ddc72128 | Python | py | |
import torch
import torch.nn as nn
import numpy as np
from sklearn.svm import LinearSVC
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import GridSearchCV
#from model.networks.ctm import reshaper,main_component,projection
class FewShotModel(nn.Module):
def __init__(self, args):
... | base.py | MIT | 2,063 | 3a66cef821d3f1e7ffe18f2d4a6b0342e7056a7d | Python | py | |
# -*- coding: utf-8 -*-
"""
Created on Thu Oct 1 10:54:40 2020
@author: josea
"""
# %% Imports
import os
import utils
import argparse
import torch
import torch.nn as nn
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from cloudmodel import CLOUD
from datetime import datetime
# %% Set-up para... | train.py | Apache-2.0 | 10,857 | 1eae5c95f37875b547dcf1b2d7a87435d8cfc0e2 | Python | py | |
# -- coding: utf-8 --
import json
import os
from cv2 import INTER_MAX
import yaml
from argparse import Namespace
from utils import render_callback, path_filler
from f110_rlenv import F110Env_Discrete_Action, F110Env_Continuous_Action, create_f110env
from baselineAgents.ppo_agent import PPOAgent
from baselineAgents.ppo_... | examples/RL_example/train_f1tenth_ppo.py | MIT | 5,905 | fdee69471be5a1f9086df66ac6d08fb6afa8a616 | Python | py | |
import torch.nn as nn
__all__ = ['SharedMLP']
class SharedMLP(nn.Module):
def __init__(self, in_channels, out_channels, dim=1):
super().__init__()
if dim == 1:
conv = nn.Conv1d
bn = nn.BatchNorm1d
elif dim == 2:
conv = nn.Conv2d
bn = nn.Batc... | modules/shared_mlp.py | MIT | 923 | f9db16183854feaeb07de11182df0a56a2a0c34f | Python | py | |
import torch.optim as optim
from model import *
import util
class trainer():
def __init__(self, scaler, in_dim, seq_length, num_nodes, nhid , dropout, lrate, wdecay, device,
supports, gcn_bool, addaptadj, aptinit, checkpoint=None):
self.model = gwnet(device, num_nodes, dropout, supports=sup... | engine.py | MIT | 2,176 | b2d10c72a942ca56e8a81ade7683983ae29901ca | Python | py | |
import tensorflow as tf
import torch
import sys
from collections import defaultdict
import pandas as pd
import numpy as np
from transformers import BertForMaskedLM, BertTokenizer
import warnings
warnings.filterwarnings('ignore')
"""
A very simple script that evaluates the bert classification model to predict wheth... | classification/eval_bert.py | MIT | 6,408 | fdf097239e018e70266b28e096d9eb38a1bb99cb | Python | py | |
import os
import time
from tqdm import tqdm
import numpy as np
import torch
from torch.utils.data import DataLoader
from torch.utils.tensorboard import SummaryWriter
import _init_path
from config import cfg
from RASF import RASF
from datasets.shapenetpart import ShapenetPartDataset, to_categorical
from utils.training... | experiments/pointclouds/shapenetpart_seg.py | Apache-2.0 | 10,470 | e632a272100c2bf2ec44022c79770b34f54df287 | Python | py | |
# Load the dataset
import torch.utils.data as data
import numpy as np
from torchvision.transforms import ToTensor, Scale, Compose, Pad, RandomHorizontalFlip, CenterCrop, RandomCrop, Resize
from PIL import Image
import torch
import os
def load_img(file_path):
img = Image.open(file_path).convert('RGB')
return ... | embedders/X2Face/UnwrapMosaic/VoxCelebData_withmask.py | Apache-2.0 | 2,070 | a96d124e788aa7194dfe96f95687ec345a1cd6e2 | Python | py | |
import torch
def feature_loss(fmap_r, fmap_g):
loss = 0
for dr, dg in zip(fmap_r, fmap_g):
for rl, gl in zip(dr, dg):
loss += torch.mean(torch.abs(rl - gl))
return loss*2
def discriminator_loss(disc_real_outputs, disc_generated_outputs):
loss = 0
r_losses = []
g_losses =... | loss.py | MIT | 820 | f930ef875e6d9bf82645097e50d7e8ccff364334 | Python | py | |
import numpy as np
import time
import torch
import torch.nn as nn
from torch.optim import Adam
from torch.optim.lr_scheduler import MultiStepLR
import dgl
from dgl.nn.pytorch import NNConv, Set2Set
from util import MC_dropout
from sklearn.metrics import r2_score, mean_absolute_error, mean_squared_error
class MPNN(... | model.py | Apache-2.0 | 7,332 | 3a676c74af9ee5518aa3eb685ee4f79159725ed4 | Python | py | |
"""
This file contains specific functions for computing losses on the RetinaNet
file
"""
import torch
from fcos_core.layers import SigmoidFocalLoss
from fcos_core.layers import smooth_l1_loss
from fcos_core.modeling.matcher import Matcher
from fcos_core.modeling.rpn.loss import RPNLossComputation
from fcos_core.struc... | fcos_core/modeling/rpn/retinanet/loss.py | BSD-2-Clause | 3,278 | 107f0e5b079e3cec1abad6badb632422fefbf570 | Python | py | |
import sys, socket, random, argparse, pickle, time
from sklearn.metrics import f1_score
import numpy as np
import torch
from trainer import get_trainer
parser = argparse.ArgumentParser(description='Training server')
parser.add_argument('--port', type=int)
parser.add_argument('--model-seed', type=int)
parser.add_arg... | named_entity_recognition/train_server.py | MIT | 2,423 | 24b195e6186ca73500f7c01f36a067a8082d2e88 | Python | py | |
import os
import torch
import torchvision
from torchvision import transforms
import torch.utils.data
from mrdataset import BrainsDataset
# Device configuration
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
WORK_DIR = './data'
BATCH_SIZE = 128
MODEL_PATH = './models'
MODEL_NAME = 'vgg19_bn.pt... | validation.py | MIT | 2,188 | 3a67dba118ae5a45e7fb222b9054abc5a753ef28 | Python | py | |
import json
import os
from enum import Enum
from typing import Optional, Dict, Any, List
import torch
from dataclasses import dataclass, field, asdict
from toolbox.Framework import is_torch_available, cached_property, torch_required
class ExplicitEnum(Enum):
"""
Enum with more explicit error message for mis... | toolbox/KGArgs.py | Apache-2.0 | 35,246 | 10ed143444e8e91c5ba8faa2c5dccf3cd75817dd | Python | py | |
import random
from collections import Counter
from typing import Dict, Optional
import numpy as np
import torch
import torch.nn.functional as F
from .backbone import BertRelationClassifier, BertTextClassifier
from .dataset import BERTTorchTextClassDataset, BERTTorchRelationClassDataset, BaseDataset, TextData... | wrench/utils.py | Apache-2.0 | 6,606 | d76916740117cc611d4cf3e5d34a09fac00750b4 | Python | py | |
"""
Custom typing extension.
Classes:
ConstantHolder: Base class for storing constants and avoiding to hardcode everything.
SaveableBaseModel: Child class of pydantic.BaseModel which enables saving and loading that BaseModel.
TypedNamedTuple: Child class of SaveableBaseModel, can be used similarly to a Nam... | utils_collection/typext.py | Apache-2.0 | 16,029 | f94cdb428291d5c22fcf46b43bb45cae4d8f6bfc | Python | py | |
# Copyright (c) Facebook, Inc. and its affiliates.
import contextlib
import os
import tempfile
import unittest
from unittest.mock import patch
import torch
from mmf.trainers.callbacks.checkpoint import CheckpointCallback
from mmf.trainers.callbacks.early_stopping import EarlyStoppingCallback
from mmf.trainers.lightni... | tests/trainers/lightning/test_checkpoint.py | BSD-3-Clause | 21,677 | fcc4ae5229f627b49cd3393a559fcf4dc1d9f266 | Python | py | |
import argparse
import logging
import os
import nni
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torchvision import datasets, transforms
logger = logging.getLogger('mnist_pbt_tuner_pytorch_AutoML')
class Net(nn.Module):
def __init__(self):
... | nni/.ipynb_checkpoints/model_pbt-checkpoint.py | MIT | 6,839 | b2e32736235828854c0ba5743468c863da19f351 | Python | py | |
from torch import optim
from data import get_cifar10_loader
from model import BarlowTwins
from config import LR, WEIGHT_DECAY
from trainer import Trainer
def main():
train_loader = get_cifar10_loader()
barlow_twins = BarlowTwins()
optimiser = optim.Adam(barlow_twins.parameters(), lr=LR, weight_decay=WE... | src/main.py | MIT | 453 | 3a684c728b4ab09596c79c8b41361e6263ca2f28 | Python | py | |
from __future__ import print_function
import argparse
import torch
import torch.utils.data
from torch import nn, optim
from torch.nn import functional as F
from torchvision import datasets, transforms
from torchvision.utils import save_image
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.... | tree/vq.py | MIT | 5,727 | 3a684f4fa25500a0aa33cebb18d7cac42ca99143 | Python | py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.