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 argparse import datetime from load_model import load_model from networks import compressor, decompressor from JPEGCompressor import jpeg_analysis from QuantizedCompressor import quantization_analysis from calculate_metrics import calculate_metrics from utils import plot_image, save_image, metrics ...
src/main.py
MIT
1,330
e60ba06be0eb0dc2e0c0efc513c6b0ba5aa6f285
Python
py
from BertFineTuning.utils import * from BertFineTuning.model_config import* import os import sys import numpy as np import pandas as pd from collections import OrderedDict from pycm import * import torch if(torch.cuda.is_available()): torch.cuda.current_device() from torch import nn from torch.utils.data import D...
BertFineTuning/model.py
BSD-2-Clause
13,811
fedb20a140f46949ba64a749a73857c2d0b72719
Python
py
"""Tests for collecting layer histogram.""" from neural_compressor.utils.collect_layer_histogram import LayerHistogramCollector from collections import OrderedDict from neural_compressor.utils import logger import numpy as np import torch import torch.nn as nn import unittest class InvertedResidual(nn.Module): def...
test/test_layer_histogram.py
Apache-2.0
4,632
fedb26f73dac358293482368ff624ab14eb2245d
Python
py
from collections import Counter import os import torch from typing import List, Optional import pandas as pd from sklearn.model_selection import train_test_split from shared.utils import save_dict_to_json def create_train_val_split( results_dir: str, df: pd.DataFrame, train_ratio: float, random_state...
src/preprocessing/data_split.py
MIT
3,186
d779cc826d6f6e4b97bb95b2d7c14ed1720838dc
Python
py
# Copyright (c) MONAI Consortium # 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...
monai/networks/nets/netadapter.py
Apache-2.0
4,591
425c1d5820893273d37244fad5fa1ce97a131983
Python
py
# ~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~ # MIT License # # Copyright (c) 2022 Nathan Juraj Michlo # # 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 Softwar...
disent/util/lightning/callbacks/_callback_log_metrics.py
MIT
6,203
b2fafead7df3bf8615c4a69d33d3ee6c2b16bef2
Python
py
import argparse import os import torch import numpy as np from model import wavefield_reconstruction np.random.seed(19) torch.manual_seed(19) parser = argparse.ArgumentParser(description='') parser.add_argument('--experiment', dest='experiment', default='interpolation', help='path of the dataset') parser.add_argument(...
src/main.py
MIT
3,042
4b60232cd16233370ae595755b07a39adc31768c
Python
py
import argparse import collections import datetime import json import os import _jsonnet import attr import torch # noinspection PyUnresolvedReferences from seq2struct import ast_util # noinspection PyUnresolvedReferences from seq2struct import datasets # noinspection PyUnresolvedReferences from seq2struct import mod...
mrat-sql-gap/seq2struct/commands/train.py
Apache-2.0
11,269
fedb3b35a63dcf15b647e503ae91a0c20a4157d4
Python
py
""" PyTorch utilities. | Copyright 2017-2021, Voxel51, Inc. | `voxel51.com <https://voxel51.com/>`_ | """ import logging import itertools import multiprocessing import sys import cv2 import numpy as np from PIL import Image import eta.core.image as etai import eta.core.learning as etal import eta.core.utils as etau ...
fiftyone/utils/torch.py
Apache-2.0
40,480
1e395b8a40f9b9974a9a66dc28ebf95cf185dc9e
Python
py
# code is based on https://github.com/katerakelly/pytorch-maml import torchvision import torchvision.datasets as dset import torchvision.transforms as transforms import torch from torch.utils.data import DataLoader,Dataset import random import os from PIL import Image import matplotlib.pyplot as plt import numpy as np ...
miniimagenet/task_generator.py
MIT
5,425
fedb510a047ed656ae2c743faccab69deee1e5a6
Python
py
import sys from sklearn import preprocessing sys.path.insert(0, '..') from qptl.qpthlocal.qp import QPFunction from qptl.qpthlocal.qp import QPSolvers from qptl.qpthlocal.qp import make_gurobi_model from SPO.sgd_learner import * from torch import optim import numpy as np import pandas as pd from sklearn.metrics i...
qptl/melding_knapsack.py
MIT
10,599
fedb726098d84eb27c2a8f16e2e187e20b1a2174
Python
py
import pytest import torch from espnet2.main_funcs.average_nbest_models import average_nbest_models from espnet2.train.reporter import Reporter @pytest.fixture def reporter(): _reporter = Reporter() _reporter.set_epoch(1) with _reporter.observe("valid") as sub: sub.register({"acc": 0.4}) ...
test/espnet2/main_funcs/test_average_nbest_models.py
Apache-2.0
1,927
ff7fe506792f5ae1e82184b5ea72570d59ca3786
Python
py
import torch import numpy as np from torch.utils.data import DataLoader from argus import load_model class StackPredictor: def __init__(self, model_path, batch_size, device='cuda'): self.model = load_model(model_path, device=device) self.batch_size = batch_size def predict(s...
src/stacking/predictor.py
MIT
781
e64de69823003d5ce211eb76bf87309d189eb609
Python
py
import torch.nn as nn from pts.flowplusplus.models.flowplusplus import log_dist as logistic from pts.flowplusplus.models.flowplusplus.nn import NN class Coupling(nn.Module): """Mixture-of-Logistics Coupling layer in Flow++ Args: in_channels (int): Number of channels in the input. mid_channel...
pts/flowplusplus/models/flowplusplus/coupling.py
Apache-2.0,MIT
1,900
fedb7dc6dff82a317f6bf5bac129da8a2b763d77
Python
py
import re import torch import torch.nn as nn from torch.nn import init import torch.nn.functional as F import torch.nn.utils.spectral_norm as spectral_norm from synchronised_batch_norm.batchnorm import SynchronizedBatchNorm2d class BaseNetwork(nn.Module): def __init__(self): super(BaseNetwork, self).__ini...
architectures/SPADE.py
MIT
7,357
b2ea6529ee96b937f3e0c4cd44c629332bff9ef1
Python
py
""" Pytorch Inception-V4 implementation Sourced from https://github.com/Cadene/tensorflow-model-zoo.torch (MIT License) which is based upon Google's Tensorflow implementation and pretrained weights (Apache 2.0 License) """ import torch import torch.nn as nn import torch.nn.functional as F from timm.data import IMAGENE...
timm/models/inception_v4.py
Apache-2.0
11,214
5f4e208f2c53e786197136ab31b18d380f73cbf1
Python
py
import argparse import os from util import util import torch import models import data class BaseOptions(): """This class defines options used during both training and test time. It also implements several helper functions such as parsing, printing, and saving the options. It also gathers additional opti...
options/base_options.py
BSD-3-Clause
8,221
5f7973d44ccaa52f28a1a43355e2182ce679a85a
Python
py
import logging import os import matplotlib.pyplot as plt import scipy import torch from scipy.stats import circmean from flows.models import NormalizingFlowModel from flows.prior_dist import * from flows.flows import * from slam.FactorGraphSolver import * import torch.optim as optim from slam.RunBatch im...
src/slam/NFiSAM.py
MIT
29,220
5f8bccecb0b929abc51ad180c23c3b5464cf94d8
Python
py
import time import pytest import torch.distributed as dist from ignite.engine import Engine, Events from ignite.metrics import Frequency def test_nondistributed_average(): artificial_time = 1 # seconds num_tokens = 100 average_upper_bound = num_tokens / artificial_time average_lower_bound = average...
tests/ignite/metrics/test_frequency.py
BSD-3-Clause
2,332
fedb943a6b4f5e8fdab518b2413f0bc64edf075c
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/local/compute_fbank_librispeech.py
Apache-2.0
3,346
b26034eb2017efe3893258a2d07e09acb70d60eb
Python
py
import torch import torchvision import torch.nn as nn import numpy as np import torchvision.transforms as transforms # ================================================================== # # Table of Contents # # ========================================================...
tutorials/01-basics/pytorch_basics/main.py
MIT
6,764
fedba12087dfb334c3aa23b11697028068063485
Python
py
import flair import torch import argparse parser = argparse.ArgumentParser(description='Train flair model') parser.add_argument('--input', '-i', help='Name of the input folder containing train, dev and test files') parser.add_argument('--output', '-o', help='Name of the ...
ner/flair_train.py
Apache-2.0
2,220
10b62d2f0341bd1c9563c7434115fc70a18861b3
Python
py
# Copyright (c) 2017-present, Facebook, 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 agreed...
test_python/layers/test_avgpool.py
Apache-2.0
1,328
fda711097816b60f97869a11f9b5703bd80f15bd
Python
py
import math import torch import numpy as np import torch.nn as nn import torch.nn.functional as F from torch.distributions.categorical import Categorical from src.util import init_weights, init_gate from src.module import VGGExtractor, CNN, ResCNN, RNNLayer, ScaleDotAttention, LocationAwareAttention from src.audio imp...
src/asr.py
MIT
16,239
fedbc95e37b90d9882754cfaafb09ee812bad5d6
Python
py
import os.path as osp from mmcv.runner import Hook from torch.utils.data import DataLoader class EvalHook(Hook): """Evaluation hook. Note that if new arguments are added for EvalHook, tools/test.py may be effected. Attributes: dataloader (DataLoader): A PyTorch dataloader. interval ...
mmdet/core/evaluation/eval_hooks.py
Apache-2.0
2,754
fedbd96455da8034bfcc1d703ab5acda10ce66fb
Python
py
import torch import torchvision from torchvision import transforms as transforms def load_CIFAR10(train_batch_size, test_batch_size): train_transform = transforms.Compose([transforms.RandomHorizontalFlip(), transforms.ToTensor(),transforms.Normalize((0.4914, 0.4822, 0.4465), (0.2023, 0.1994, 0.2010))]) test_t...
datasets.py
Apache-2.0
1,775
d7e77f0b43d40bb0a329cd1c68d6c9b9d56822e4
Python
py
# -*- coding:utf-8 -*- # Author: hankcs # Date: 2021-01-06 16:12 from typing import List from elit.common.dataset import SortingSamplerBuilder from elit.common.transform import NormalizeToken from elit.components.mtl.loss_balancer import MovingAverageBalancer from elit.components.mtl.multi_task_learning import MultiTa...
stem_cell_hypothesis/en_bert_large/joint/dep_srl.py
Apache-2.0
4,739
5e1a68d0ae6544926731d65d4eb03f94316325c9
Python
py
# AUTOGENERATED! DO NOT EDIT! File to edit: nbs/data_loader.ipynb (unless otherwise specified). __all__ = ['oversample', 'TextMelDataset', 'TextMelCollate', 'TextAudioSpeakerLoader', 'TextAudioSpeakerCollate', 'DistributedBucketSampler'] # Cell import os import random import re from pathlib import Path fro...
uberduck_ml_dev/data_loader.py
Apache-2.0
19,331
fedbf57b696be0107587ccad291f510caff7a869
Python
py
""" Instance-Segmentation-Projects Nick Kaparinos 2021 """ import math import sys import torchvision.models.detection.mask_rcnn import wandb from coco_eval import CocoEvaluator from coco_utils import get_coco_api_from_dataset from utilities import * def train_one_epoch(model, optimizer, data_loader, device, epoch, p...
engine.py
MIT
4,112
fd933cb3a4b09ec5fb5dde02009c2a25b4d14c47
Python
py
import numpy as np import os import torch import torch.nn as nn from models.helper import build_generator PGGAN_Inter_Output_Layer_256 = [-1, 17, 14, 11, 8, 5, 2] PGGAN_Inter_Output_Layer_1024 = [-1, 23, 20, 17, 14, 11, 8, 5, 2] def standard_z_sample(size, depth, device=None): ''' Generate a standard set o...
derivable_models/gan_utils.py
MIT
1,590
d79bb33531558a7f5b179887da5d95e0faf89766
Python
py
""" Compute the style and content loss using a VGG-16 model trained on ImageNet. Uses perceptual loss to compute the style and content loss. """ import torch import torchvision from collections import namedtuple LossOutput = namedtuple( "LossOutput", ["relu1_2", "relu2_2", "relu3_3", "relu4_3"]) def gram_matrix...
src/perceptual_loss_net.py
MIT
3,974
4b42fa2118f548456eff9ad799b75b043b4c4f17
Python
py
import torch # import hyperparams as hyp import numpy as np import utils.utils_geom as utils_geom import utils.utils_samp as utils_samp # import utils.utils_improc as utils_improc import utils.utils_basic as utils_basic import torch.nn.functional as F from utils.utils_basic import * class Vox_util(object): def __i...
script/utils/utils_vox.py
MIT
40,769
fedc1ae4ea95ff4483052eaf81cc6b1bb37bf56f
Python
py
from colossalai.amp import AMP_TYPE from model_zoo.gpt.gpt import GPTLMLoss, gpt2_small from torch.optim import Adam #from deepspeed.ops.adam import DeepSpeedCPUAdam BATCH_SIZE = 1 NUM_EPOCHS = 60 SEQ_LEN = 1024 zero = dict( level=3, dynamic_loss_scale=True, overlap_comm=True, clip_grad=1.0, offl...
language/gpt/gpt2_configs/gpt2_nvme.py
Apache-2.0
1,018
e61e3fd56de58f0b1b1cd262d06512380717c4ab
Python
py
from PIL import Image import torchvision.transforms as transforms import matplotlib.pyplot as plt import torch import numpy as np import cv2 label_names = { 0: "NORMAL", 1: "CNV", 2: "DME", 3: "DRUSEN", } CLS2IDX = label_names # rule 5 from paper def avg_heads(cam, grad): cam = cam.reshape(-1, ca...
facebook_dino/mm_dino.py
Apache-2.0
4,726
34254408e7e49cbcf98c7527f8d99aa2ec191928
Python
py
import torch import math import os import sys import logging from graphgym.config import cfg from graphgym.utils.io import dict_to_json, dict_to_tb import pdb from sklearn.metrics import * from tensorboardX import SummaryWriter def setup_printing(): logging.root.handlers = [] logging_cfg = {'level': logging....
graphgym/logger.py
MIT
6,402
fedc56d1487618267ad1b580afc43463a685babb
Python
py
from networks import common import torch import torch.nn as nn import math import numpy as np def make_model(args, parent=False): return RCAN(args) ## Channel Attention (CA) Layer class CALayer(nn.Module): def __init__(self, channel, reduction=16): super(CALayer, self).__init__() # global avera...
networks/rcan_v3.py
MIT
5,931
700b512d28655331bc4a1eb695e4cba7889e02d6
Python
py
# Copyright (c) 2022, 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/modules/common/megatron/megatron_encoders.py
Apache-2.0
4,350
fedc5a6651ca346a8f3884bf3e7ed34e8ec898a0
Python
py
import copy import logging import torch import numpy as np import wandb from fedml_api.standalone.fednova.client import Client class FedNovaTrainer(object): def __init__(self, dataset, model, device, args): self.device = device self.args = args [train_data_num, test_data_nu...
fedml_api/standalone/fednova/fednova_trainer.py
Apache-2.0
11,066
4578d794fb8fa2af257a512faad883a1ff85bc18
Python
py
##+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ ## Created by: Yaoyao Liu ## Modified from: https://github.com/hshustc/CVPR19_Incremental_Learning ## Max Planck Institute for Informatics ## yaoyao.liu@mpi-inf.mpg.de ## Copyright (c) 2021 ## ## This source code is licensed under the MIT-style...
classification/models/modified_resnet.py
MIT
4,339
fedc6eb22a66bae9798fdb590f8309b03d21aaa7
Python
py
import torch import matplotlib.pyplot as plt import numpy as np def saliency(img, model, save_path): # We don't need gradients wrt weights for a trained model for param in model.parameters(): param.requires_grad = False model.eval() input = torch.from_numpy(img).float().unsqueeze(0) # Ge...
rlpyt/utils/saliency.py
MIT
1,064
fedc7dd7ef63afe3a402a3f621ad1a82ffa2f7e9
Python
py
# Copyright (c) 2021 Graphcore Ltd. All rights reserved. # Copyright 2019 Shigeki Karita # 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, software...
applications/pytorch/conformer/src/layers/positionwise_feed_forward.py
MIT
1,373
fedc8309414cda583757b8a46d567ca53ffd5157
Python
py
import torch import torch.nn as nn class Upsample(nn.Module): def __init__(self, scale_factor, mode="bilinear"): super().__init__() self.scale_factor = scale_factor self.mode = mode def forward(self, input): return nn.functional.interpolate(input, scale_factor=self.scale_facto...
example_specs/models/unet2d_nuclei_broad/unet2d.py
MIT
2,398
fedc9be1055ac76da560a87d77c72328e339ab70
Python
py
# -*- coding: utf-8 -*- """ Created on Wed Jul 11 10:28:06 2018 @author: herminarto.nugroho """ import pandas as pd import numpy as np from PIL import Image import torch from torchvision import transforms from torch.utils.data.dataset import Dataset # For custom datasets from torch.utils.data.sampler import SubsetR...
src/custom_datasets.py
MIT
3,394
fedca1dd8ece7252ca6c02bfeaff1eea9129094c
Python
py
""" DRN for ImageNet-1K, implemented in PyTorch. Original paper: 'Dilated Residual Networks,' https://arxiv.org/abs/1705.09914. """ __all__ = ['DRN', 'drnc26', 'drnc42', 'drnc58', 'drnd22', 'drnd38', 'drnd54', 'drnd105'] import os import torch.nn as nn import torch.nn.init as init class DRNConv(nn.Module): ...
pytorch/pytorchcv/models/drn.py
MIT
18,826
fedca2c078c7106ab73f8fa22cf520ace6e86b39
Python
py
import torch from torch.nn import functional as F __all__ = ["RoundSTE", "logit", "sum_except_batch", "to_discrete"] class RoundSTE(torch.autograd.Function): @staticmethod def forward(ctx, inputs): return inputs.round() @staticmethod def backward(ctx, grad_output): """Straight-throug...
dlfairness/original_code/nifr/nifr/utils/torch_ops.py
BSD-3-Clause
804
5e66e0562c0b4887a59a1ba929a9ed42d43586f5
Python
py
import torch import torch.nn as nn class NeuralNet(nn.Module): def __init__(self, input_size, hidden_size, num_classes): super(NeuralNet, self).__init__() self.l1 = nn.Linear(input_size, hidden_size) self.l2 = nn.Linear(hidden_size, hidden_size) self.l3 = nn.Linear(hidden_size, n...
model.py
MIT
602
a95dfe2954338cc920e533ae54d7f4357a8fa1ea
Python
py
import yaml import argparse import numpy as np import os import sys import time import json import pickle import torch as th import torch.nn as nn from kaldi.util.table import MatrixWriter from kaldi.util.io import read_matrix from data import SpeechDataset, SeqDataloader from models import LSTMStack, NnetAM def ma...
decode.py
MIT
5,218
a98a8011ec768d378ac466f2d29a9c3d6f27ba70
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/trainer/connectors/test_signal_connector.py
Apache-2.0
1,907
1ec62f3d3082f3615fc3cea0c247c160a235099b
Python
py
import argparse import os import torch import tempfile from tqdm import tqdm from mlprogram import logging from mlprogram.entrypoint.configs import load_config, parse_config from app import types logger = logging.Logger(__name__) def main() -> None: parser = argparse.ArgumentParser() parser.add_argument("-...
tools/ideal_accuracy.py
MIT
1,044
3474c13685edae8fba68c563b5cec28c3352e595
Python
py
# coding=utf-8 # Copyright 2022 The OpenBMB 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 a...
model_center/model/config/vit_config.py
Apache-2.0
2,034
24715476ca402be15c2836e4c7e5e83b3cb02d96
Python
py
import os import sys from torchtext import data, datasets import sentencepiece as spm import pandas as pd import MeCab def English_tokenizer(): df = pd.read_csv("test_sample.csv") ENG_data = df['English'] f = open("eng.txt", "w", encoding = 'utf-8') for row in ENG_data[:100000]: f.wr...
tokenizer/English_tokenizer.py
Apache-2.0
725
6531670ebb1ba0a646eeeecf3d3df7fca8e4a1c3
Python
py
import torch import torch.nn as nn class Conv6(nn.Module): def __init__(self, in_ch, imgsz, num_classes=10): super(Conv6, self).__init__() self.conv1 = nn.Conv2d(in_ch, 64, kernel_size=(3, 3), stride=1, padding=1) self.conv2 = nn.Conv2d(64, 64, kernel_size=(3, 3), stride=1, padding=1) self.conv3 = nn...
models/bare/conv6.py
MIT
1,263
a94c5e885be267ec7fc943fb799b4b7e7444b6c7
Python
py
#!/usr/bin/env python3 # Copyright (c) Meta Platforms, Inc. and affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. from typing import Any, Callable, Dict, List, Optional, Tuple import torch from ax.core.search_space import SearchSp...
ax/models/torch/rembo.py
MIT
10,109
e607aa90c37de00eebef257147b8cd7a99a64192
Python
py
import json import math import os import pickle import random from collections import defaultdict import dgl import numpy as np import torch from torch.utils.data import IterableDataset, DataLoader from transformers import * from models.GAIN import Bert from utils import get_cuda IGNORE_INDEX = -100 class DGLREDat...
code/.ipynb_checkpoints/data-checkpoint.py
MIT
30,824
fedd6e7046d576fd6df22124d28fd69b8e033b35
Python
py
import torch import torch.nn as nn import torch.nn.functional as F import torch_geometric from torch_geometric.data import Data from torch_geometric.nn import TransformerConv from constant import * from util_module import make_full_graph, get_seqsep class UniMPBlock(nn.Module): '''https://arxiv.org/pdf/2009.0350...
hallucination/models/rf_Nov05_2021/InitStrGenerator.py
MIT
4,104
fdd858e2e7d9cc0c0d9de8c8e7df4c376b8ceba7
Python
py
############################################################################### # Author: Wasi Ahmad # Project: https://www.microsoft.com/en-us/research/wp-content/uploads/2016/10/wwwfp0192-mitra.pdf # Date Created: 7/23/2017 # # File Description: This script is the entry point of the entire pipeline. ###########...
ranking_baselines/DUET/main.py
MIT
3,130
dfcfe3ffb1ded9df328c36b66e4bcb630fd74539
Python
py
import os import numpy as np import torch from torch.utils.data import Dataset, DataLoader from scipy.misc import imread, imresize, imsave class CustomDataSet(Dataset): def __init__(self, input_dir, input_height, input_width): self.input_dir = input_dir self.input_size = [input_height, input_widt...
dataset.py
MIT
2,323
342938eb7f643ba5ecbe803afee51322599d7fd8
Python
py
from __future__ import absolute_import, division, print_function from easydict import EasyDict as edict import numpy as np import pickle import torch import torch.nn as nn import torch.nn.functional as F from utils import * from data_utils import AmazonDataset class KnowledgeEmbedding(nn.Module): def __init__(s...
models/PGPR/transe_model.py
MIT
22,485
10fa04db046137d09d91d869d03c97af712708f1
Python
py
from dataclasses import dataclass, field from typing import List, Optional import torch from omegaconf import DictConfig from torch.optim.lr_scheduler import _LRScheduler from ..dataclass.configurations import LearningRateSchedulerConfigs from . import register_scheduler class ExponentialLR(_LRScheduler): """Ex...
fulmo/schedulers/expontial.py
MIT
2,858
1e7828e1d9c9c0febf8e57e381ca166c4b6ca8ec
Python
py
from __future__ import print_function import argparse import torch import torch.nn.parallel import torch.utils.data from torch.autograd import Variable from pointnet.dataset import ShapeNetDataset from pointnet.model import PointNetCls import torch.nn.functional as F #showpoints(np.random.randn(2500,3), c1 = np.rando...
utils/show_cls.py
MIT
1,485
6b23e0b1e6357dca0f36fb8e86db8090568da78a
Python
py
from starlette.applications import Starlette from starlette.templating import Jinja2Templates import uvicorn import aiohttp import asyncio import sys from io import BytesIO from PIL import Image import base64 import cv2 import numpy as np import torch from fastai import vision from skimage.morphology import label # Re...
airbus-ship-segmentation/app/server.py
MIT
4,877
12f5aac9b29b9571977ce1f258c404d93e5cc925
Python
py
""" This code evaluates bert """ import argparse import logging from tqdm import tqdm import numpy as np import os os.environ['CUDA_VISIBLE_DEVICES'] = '1' import torch from torch.utils.data.dataloader import DataLoader from transformers.data.processors import glue_processors, glue_output_modes from transformers.dat...
WorkSpace/bert-eval.py
Apache-2.0
4,165
28bbbf0715de589841c13e03352a3ea56be4504b
Python
py
import argparse import os import sys import torch def parse_commandline_arguments(): parser = argparse.ArgumentParser(description='iTracker-pytorch-Trainer.') #---------- Experimental Configuration ------------ parser.add_argument('--data_path', help='Path to dataset folder contain...
utility_functions/argument_parser.py
RSA-MD
8,603
feddfbfcdaae377ae4aa4074a6a75ccafe752be2
Python
py
import torch import torch.nn as nn def weights_init(m): classname = m.__class__.__name__ if classname.find('Conv') != -1: m.weight.data.normal_(0.0, 0.02) elif classname.find('BatchNorm') != -1: m.weight.data.normal_(1.0, 0.02) m.bias.data.fill_(0) class PyBulletEncoder(nn.Module...
swae/models/custom.py
MIT
5,071
b2baf8e342b97e81f361c2b21fcba60993d50a76
Python
py
"""Auxiliary dataset functions This module provides generic functions related to all datasets """ from torch.utils.data import Dataset import torch NUM_WORKERS = 0 def get_dataset_with_index(dataset, offset): class DatasetWithIndex(type(dataset)): def __getitem__(self,index): retu...
src/indirect_method/utils_dataset.py
MIT
2,738
1ed460cf35d3dbc034d20608ab282a35c69916fb
Python
py
""" This script is the agent implementation of a Deep Deterministic Policy Gradient agent on the Unity Reacher environment. The base model, agent and training function were taken from the solution here: https://github.com/udacity/deep-reinforcement-learning/tree/master/ddpg-pendulum. It was modified to include paramet...
agent.py
MIT
11,062
24d9b774106f7171b539c97ea54a0b2acab23d32
Python
py
# ------------------------------------------------------------------------------ # Torchvision requires the mean and standard deviation to be calculated manually # for normalization. This method can be used for that. However, this is mainly # for colored 2D images and therefore rarely relevant for medical data. # ---...
mp/utils/pytorch/compute_normalization_values.py
MIT
1,064
03a619d8c268d47a14c60012f9e6c4c43c0a354c
Python
py
import argparse import dgl import math import numpy as np import os import time import torch import torch.nn.functional as F from torch.optim.lr_scheduler import LambdaLR from tqdm import tqdm import utils from model import * np.random.seed(12345) torch.manual_seed(12345) torch.cuda.manual_seed(12345) class Cosin...
UnsupervisedNodeClassification/Model/DMPNN/src/main.py
MIT
11,408
fede6ca0966bb7e09cd157fdf51e46ae1b395c75
Python
py
import torch import torch.nn.functional as F import torch.nn as nn from torch_geometric.utils import degree from models_misc import mlp from ogb.graphproppred.mol_encoder import AtomEncoder, BondEncoder from ogb.utils.features import get_atom_feature_dims, get_bond_feature_dims def multi_class_accuracy(y_hat, y, re...
utils_graph_learning.py
MIT
9,658
fede70154b56201c1e230f3415aa5c2c0a70bb2a
Python
py
import argparse import os import cv2 from tqdm import tqdm import numpy as np import torch from torch.autograd import Variable def main(): files = [ 'car1.mp4', 'car2.mp4', 'ped1.mp4', 'ped2.mp4', 'ped3.mp4', 'ped4.mp4', 'ped5.mp4', 'ped6.mp4', ...
video_left_right.py
MIT
2,998
7c6b53b630d5bb6d16460017e3b07954250034d5
Python
py
import os os.environ['KMP_DUPLICATE_LIB_OK']='True' import math import numpy as np from scipy import linalg from os import path as osp import cv2 import random import matplotlib.pyplot as plt import pdb #0. torch imports import torch from torch.utils.data import DataLoader,Dataset from torch import optim,nn import tor...
full_code/train_oneclass.py
MIT
67,469
fede821263881e01216e808271ca9231ff601815
Python
py
# speed up the loading of the training data import cv2 import numpy as np import torch as th import itertools import torch.nn as nn import torch.nn.functional as F import torch.nn.init as init from gan.src.model import NetG, NetD, NetA from gan.src.data_set import LookbookDataset import torch.optim as optim import visd...
gan/src/train.py
MIT
4,931
fcc0def59a26241ff60e9531605b4e20a9362f3e
Python
py
import logging import torch.nn as nn from ..trainer import load_checkpoint class AlexNet(nn.Module): """AlexNet backbone. Args: num_classes (int): number of classes for classification. """ def __init__(self, num_classes=-1): super(AlexNet, self).__init__() self.num_classes ...
det3d/torchie/cnn/alexnet.py
MIT
1,932
28db64190d079b5416ad6bd4d20760069a4b3c12
Python
py
import sys import math import functools import numpy as np import torch import torch.nn as nn import torch.nn.functional as F sys.path.append('utils') from proj_adaptive_softmax import ProjectedAdaptiveLogSoftmax from log_uniform_sampler import LogUniformSampler, sample_logits class PositionalEmbedding(nn.Module): ...
examples/enwik8_tf/mem_transformer.py
MIT
30,964
e6377264d8002f132e9cb1533af923b11dd3ac95
Python
py
import os import torch import yaml import numpy as np from PIL import Image import cv2 import torch.nn.functional as F def pil_loader(path): # open path as file to avoid ResourceWarning (https://github.com/python-pillow/Pillow/issues/835) with open(path, 'rb') as f: img = Image.open(f) return...
utils/tools.py
MIT
17,889
341324c7538e278b269a7b3a75b6a092bd861bbc
Python
py
import argparse from typing import Any, List, Sequence import torch from torch import nn from cassle.distillers.base import base_distill_wrapper from cassle.losses.simclr import simclr_distill_loss_func def contrastive_distill_wrapper(Method=object): class ContrastiveDistillWrapper(base_distill_wrapper(Method)):...
cassle/distillers/contrastive.py
MIT
2,687
fedecd2636fb07cd2b25eadf1e34884e4f491de6
Python
py
# modified from https://github.com/lioryariv/idr/blob/main/code/datasets/scene_dataset.py import os import json import torch import numpy as np from tqdm import tqdm from utils.io_util import load_mask, load_rgb, glob_imgs from utils.rend_util import rot_to_quat, load_K_Rt_from_P class SceneDataset(torch.utils.data....
dataio/custom.py
MIT
6,099
a91412c1a8cd5937c2fd4ee6c79a9caa8000692a
Python
py
import torch import torchvision from torch.utils.mobile_optimizer import optimize_for_mobile print(torch.__version__) model = torchvision.models.detection.fasterrcnn_mobilenet_v3_large_320_fpn( pretrained=True, box_score_thresh=0.7, rpn_post_nms_top_n_test=100, rpn_score_thresh=0.4, rpn_pre_nms_top_n_test=150 ) ...
android/test_app/make_assets.py
BSD-3-Clause
486
fedee39fc52b50090dcbada630e753cb477d6a8b
Python
py
import io import torch from torchvision import ops from torchvision import models from torchvision.models.detection.image_list import ImageList from torchvision.models.detection.transform import GeneralizedRCNNTransform from torchvision.models.detection.rpn import AnchorGenerator, RPNHead, RegionProposalNetwork from to...
test/test_onnx.py
BSD-3-Clause
21,051
03cd6ceb3a5ec9c708fcf30686db2d2dacb77296
Python
py
import torch import dgl import numpy as np from types import SimpleNamespace from src.problem.tsptw.environment.tsptw import TSPTW from src.problem.tsptw.learning.actor_critic import ActorCritic from src.architecture.graph_attention_network import GATNetwork class SolverBinding(object): """ Definition of th...
src/problem/tsptw/solving/solver_binding.py
MIT
8,299
70a697060a4c451d27bdd9acbe94808c82311bbd
Python
py
try: import cv2 except ImportError: import sys sys.path.remove('/opt/ros/kinetic/lib/python2.7/dist-packages') import cv2 import torch, torchvision import torch.nn as nn import torch.nn.functional as F from torchvision.models.resnet import Bottleneck import numpy as np from itertools import product fro...
yolact.py
MIT
30,595
03a89043f961af748adebcc12a7a79140f31b063
Python
py
if __name__ == '__main__': import os import torch from torch.utils.data import DataLoader from networks import Discriminator, Generator, Loss from options import TrainOption from pipeline import CustomDataset from utils import Manager, update_lr, weights_init import numpy as np from ...
train.py
MIT
5,348
fedf310cf2e632fcb4dd67b1be30693b83aba321
Python
py
from functools import wraps import pandas as pd def from_dataframe_cache(key): """Returns a decorator that wraps a function with signature, (params: dict, force: bool, kwargs) that returns a pandas Dataframe. The ``params[key]`` should be a :class:`pathlib.Path` to save and load the cached datafr...
{{cookiecutter.repo_name}}/utils.py
MIT
2,689
654da1c0029ebac0048f8765faf5b6d35beb5c5a
Python
py
from __future__ import absolute_import import sys import numpy as np import torch from torch import nn import os from collections import OrderedDict from torch.autograd import Variable import itertools from .base_model import BaseModel from scipy.ndimage import zoom import fractions import functools import skimage.tr...
models/dist_model.py
BSD-2-Clause
17,286
fdd7bfec0af8486bac5351083be442b47c2a88ff
Python
py
import glob import math import os import random import shutil import subprocess import time from copy import copy from pathlib import Path from sys import platform import cv2 import matplotlib import matplotlib.pyplot as plt import numpy as np import torch import torch.nn as nn import torchvision import yaml from scip...
utils/utils.py
MIT
52,729
7cc1d9ca95d9d847d9ca0b31439bdb248e1e273e
Python
py
# Copyright (c) 2017-2019 Uber Technologies, Inc. # SPDX-License-Identifier: Apache-2.0 import math import pytest import torch import pyro import pyro.distributions as dist import pyro.poutine as poutine from pyro.infer.importance import psis_diagnostic from pyro.infer.util import MultiFrameTensor from tests.common ...
tests/infer/test_util.py
Apache-2.0
2,397
45f58072951d221d5e809fdaa88af04e294e87c3
Python
py
import logging import numpy as np import torch import torch.utils.data class PairDataset(torch.utils.data.Dataset): AUGMENT = None def __init__( self, root, phase, voxel_size=0.05, transform=None, rotation_range=360, random_rotation=True, seed=...
src/data/base_loader.py
MIT
927
e659e7927798660e3a5d8de1cdaacb853b88d99b
Python
py
# -*- coding: utf-8 -*- """Untitled2.ipynb Automatically generated by Colaboratory. Original file is located at https://colab.research.google.com/drive/1shr64TH78pZ1t28uNBguw-Ul2S5jhaCB """ from google.colab import auth auth.authenticate_user() from google.colab import drive drive.mount('/content/gdrive') cd /...
ai/KoBert/Model.py
MIT
3,503
6b4026d8e6b203c977c2e063df35540101fc32fb
Python
py
# Owner(s): ["oncall: quantization"] # Torch import torch from torch.ao.quantization import ( MinMaxObserver, PerChannelMinMaxObserver, MovingAverageMinMaxObserver, MovingAveragePerChannelMinMaxObserver, HistogramObserver, RecordingObserver, PlaceholderObserver, NoopObserver, FakeQu...
test/quantization/core/test_workflow_module.py
Intel
53,244
1e910003a9c35f65782273f02aee973642c1b121
Python
py
""" 3D IoU Calculation and Rotated NMS Written by Shaoshuai Shi All Rights Reserved 2019-2020. """ import torch from ...utils import common_utils from . import iou3d_nms_cuda def boxes_bev_iou_cpu(boxes_a, boxes_b): """ Args: boxes_a: (N, 7) [x, y, z, dx, dy, dz, heading] boxes_b: (N, 7) [x, ...
btcdet/ops/iou3d_nms/iou3d_nms_utils.py
Apache-2.0
4,276
7ce65fe48c8e0ad9a30e8e1ca4b8cb9f54eeab27
Python
py
from __future__ import absolute_import from __future__ import division from __future__ import print_function import sys import _init_paths import os # os.environ['CUDA_VISIBLE_DEVICES'] = "0,1,2,3,4,5,6,7" import torch import torch.utils.data from opts import opts from models.model import create_model, load_model, sav...
src/main.py
MIT
4,085
fedff0781020c714f99d30d26af2c15dd9121112
Python
py
# Copyright 2020 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...
train.py
Apache-2.0
16,919
249eef54f4d2e92bdb11b9ddd263b5d2712ea053
Python
py
import os import torch import torch.nn as nn import torch.nn.functional as F from torch.nn.utils.rnn import pack_padded_sequence import numpy as np import random from .lrcn_trainer import LRCNTrainer class GVETrainer(LRCNTrainer): REQ_EVAL = True def __init__(self, args, model, dataset, data_loader, logger...
train/gve_trainer.py
MIT
3,665
fedff6d8ff7e4cda598f5f39c090c802dfb29cea
Python
py
##+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ ## Created by: Hang Zhang ## Email: zhanghang0704@gmail.com ## Copyright (c) 2018 ## ## This source code is licensed under the MIT-style license found in the ## LICENSE file in the root directory of this source tree ##++++++++++++++++++++++++++...
encoding/functions/syncbn.py
MIT
10,894
e60f6b44a73481736bbd7c55e0e3ffa2214c0ae9
Python
py
import torch import torch.nn as nn import torch.nn.functional as F from torch.autograd import Variable from layers import * from data import voc, coco import os from binarized_modules import BinarizeLinear,BinarizeConv2d class SSD(nn.Module): """Single Shot Multibox Architecture The network is composed of a...
ssd.py
MIT
9,120
fedfff5319b9db9f67e214ba82ef184c14ee4656
Python
py
""" Here, we revisit the 2D board env, since continuous-control with our prior RL-understanding refused to be solved, a few times already. This time, to remove prediction-interference: the env's action needs 4 numbers, and is decided by which is higher. Open-ended algorithms, to prepare for any goal, learn min-distan...
py/test_board_revisit.py
MIT
19,117
fee000293faf9b99cced78ff6961d04628bffa82
Python
py
#!/usr/bin/env python # coding: utf-8 import torch import graphgallery print("GraphGallery version: ", graphgallery.__version__) print("Torch version: ", torch.__version__) ''' Load Datasets - cora/citeseer/pubmed ''' from graphgallery.datasets import Planetoid data = Planetoid('cora', root="~/GraphData/datasets/", ...
examples/Graph_Neural_Networks/PyTorch/SBVAT.py
MIT
767
fee00ac927df95c3524645994fa686e9381dd978
Python
py
#!/usr/bin/env python # -*- coding: utf-8 -*- # author: yizhong # created_at: 17-5-23 下午6:15 import torch import torch.nn as nn class BasicRecursiveNN(nn.Module): def __init__(self, word_vocab_size, word_embed_dim, hidden_size, use_cuda): super(BasicRecursiveNN, self).__init__() self.use_cuda = us...
src/models/basic_recursive_nn.py
MIT
1,734
fee05302fb9e8dde01c985df7aa2f9750e0684da
Python
py
import glob import os import shutil import unittest import torch from torch.utils.data import ConcatDataset from transformers import TextDataset, AutoTokenizer, TrainingArguments, DataCollatorForLanguageModeling, \ PreTrainedTokenizer, BertForMaskedLM, AutoConfig, XLMRobertaForMaskedLM from continued_pretraining....
continued_pretraining/test/test_cont_trainer.py
MIT
7,299
52eeee9107b7d75e115763c09fa8fd8f7d31e172
Python
py
import os from typing import List, Tuple from torch.utils.data import Dataset import data import numpy as np class InferenceDataset(Dataset): def __init__(self, data_root: str, file_list: List[str], file_extension: str, data_type: str, transformation=None, scan_dataset: str = "scannet", cad_data...
src/data/inference_dataset.py
MIT
4,126
45463a0d3816f3b0c7619ba233e4e694c7decb5a
Python
py