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 |
|---|---|---|---|---|---|---|---|
# -*- coding: utf-8 -*-
"""
@Time : 2021/1/16 上午10:46
@FileName: LSTM.py
@author: 王炳宁
@contact: wangbingning@sogou-inc.com
"""
import torch
import torch.nn as nn
from torch.nn import functional as F
class LSTM(nn.Module):
def __init__(self, vocab_size, n_embedding, n_hidden, n_layer):
super().__in... | modules/LSTM.py | Apache-2.0 | 1,377 | 299f4d58e47faaaf5a8548c99b7199080ba65508 | Python | py | |
# @Time : 2021/12
# @Author : Yong Zheng
# @Notes : Inherit from recbole.evaluator.Collector
"""
recbole.evaluator.collector
################################################
"""
from recbole.evaluator.register import Register
from recbole.evaluator import Collector, DataStruct
import torch
class CARSCollector(Co... | deepcarskit/evaluator/collector.py | MIT | 3,681 | 299f51d5e73d3da3038c2c70db36a950790678b9 | Python | py | |
"""This file is a simple example script training a CNN model on mel spectrograms."""
import argparse
import logging
from copy import deepcopy
from pathlib import Path
from typing import Callable, List, Optional, Union
import torch
from torch.utils.data import ConcatDataset, DataLoader
from torchaudio.functional import... | train_models.py | MIT | 14,047 | 4b43317b620a76445cb488ce5bb7e354b436d2f1 | Python | py | |
import numpy as np
import torch
from utils.helpers import process_state, device
def make_epsilon_greedy_policy(estimator, nA):
"""
:param estimator: model that returns q values for a given statem/action pair
:param nA: number of actions in the environment
:return: A function that takes in a state and ... | policy.py | MIT | 920 | 299f9a135fb0ac674c3200f9214021f3cf9fd561 | Python | py | |
import time
import os
import sys
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from ..attack import Attack
class APGD(Attack):
r"""
APGD in the paper 'Reliable evaluation of adversarial robustness with an ensemble of diverse parameter-free attacks'
[https://arxiv... | torchattacks/attacks/apgd.py | MIT | 12,484 | 4b391603b91067e14d130979f586fe64fc77582c | 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 parlai.core.agents import create_agent_from_shared
from parlai.mturk.core.agents import TIMEOUT_MESSAGE
from parlai.core.worlds import vali... | ParlAI/projects/controllable_dialogue/mturk/worlds.py | MIT | 31,814 | 299fe629a3e5ef65882f40a43b0aefda61aecac1 | Python | py | |
# -*- coding: utf-8 -*-
"""Tests for the All-CNN-C architecture on the CIFAR-100 dataset."""
import os
import sys
import unittest
import torch
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))
from deepobs.pytorch import testproblems
class Cifar100_AllCNNCTest(unittes... | tests/pytorch/testproblems/test_cifar100_allcnnc.py | MIT | 1,294 | 4266bdb53ffa988406ca0cf2bcb52a0ae8c912b5 | Python | py | |
import torch
import torch.nn as nn
import torch.nn.functional as F
from utils.masking import TriangularCausalMask, ProbMask
from layers.Transformer_EncDec import Decoder, DecoderLayer, Encoder, EncoderLayer, ConvLayer
from layers.SelfAttention_Family import FullAttention, ProbAttention, AttentionLayer
from layers.Embed... | models/Informer.py | MIT | 3,336 | 299fecc3d51efd67a4f4d177efe1960908d37247 | Python | py | |
# coding=utf-8
# Copyright 2018 The Google AI Language Team Authors, Facebook AI Research authors and The HuggingFace Inc. team.
# Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the L... | modeling_utils.py | BSD-3-Clause | 80,224 | 458e5bac4ae2dc211a651f89f1c86a162964711a | Python | py | |
import torch.optim as optim
from run_utils.callbacks.base import (
AccumulateRawOutput,
PeriodicSaver,
ProcessAccumulatedRawOutput,
ScalarMovingAverage,
ScheduleLr,
TrackLr,
VisualizeOutput,
TriggerEngine,
)
from run_utils.callbacks.logging import LoggingEpochOutput, LoggingGradient
fro... | models/hovernet/opt_second_order.py | MIT | 4,858 | 12b9dac69ed4cbab2cde8ac0d96c1281415b1bb3 | Python | py | |
# --------------------------------------------------------
# Tensorflow Faster R-CNN
# Licensed under The MIT License [see LICENSE for details]
# Written by Xinlei Chen
# --------------------------------------------------------
from __future__ import absolute_import
from __future__ import division
from __future__ impor... | lib/model/faster_rcnn/vgg16_global.py | MIT | 3,764 | 29a01c354ed5543c66cf3db2473d21a036f1196b | Python | py | |
import glob
import torch.utils.data as data
import torchvision.transforms as transforms
from PIL import Image
class AlignedDataset(data.Dataset):
def __init__(self, data_dir, direction, img_size):
super(AlignedDataset, self).__init__()
self.AB_dir = '{}'.format(data_dir)
se... | dataset.py | MIT | 1,169 | 29a01e2c1d491ac7086fb2073542a56d8c466c2c | Python | py | |
# Copyright 2016-present, Facebook, Inc.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
import torch, numpy as np
import plyfile
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.aut... | examples/ScanNet/utils.py | BSD-3-Clause | 16,759 | 29a02bebf77fd73eac36616781c3d587ee58302d | Python | py | |
#!/usr/bin/env python3
import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
import itertools
import utils
import random
class ConstituencyTreeCRF(nn.Module):
def __init__(self):
super(ConstituencyTreeCRF, self).__init__()
self.huge = 1e9
def logadd(self, x, y):
d = ... | urnng/TreeCRF.py | MIT | 6,934 | 29a037d3fe02a50344c8d881fc67ef7ad378cf00 | Python | py | |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Python version: 3.6
import copy
import torch
from torch import nn
def FedAvg(w):
w_avg = copy.deepcopy(w[0])
for k in w_avg.keys():
for i in range(1, len(w)):
w_avg[k] += w[i][k]
w_avg[k] = torch.div(w_avg[k], len(w))
return w_av... | models/Fed.py | MIT | 322 | 29a03d175c6edffd2e73626a42c15fc6cb04a9d0 | Python | py | |
import os
import torch
from src import deeplabv3_resnet50
from train_utils import evaluate
from my_dataset import VOCSegmentation
import transforms as T
class SegmentationPresetEval:
def __init__(self, base_size, mean=(0.485, 0.456, 0.406), std=(0.229, 0.224, 0.225)):
self.transforms = T.Compose([
... | Deep-Learning-Notes/Segmentation/deeplab_v3/validation.py | MIT | 2,406 | 1053651a02c9a34748f279f2e9640cc9fa468fb9 | Python | py | |
import os
import torch
import numpy as np
from copy import deepcopy
from pprint import pprint
'''config for agent'''
class Arguments:
def __init__(self, agent, env=None, env_func=None, env_args=None):
self.env = env # the environment for training
self.env_func = env_func # env = env_func(*env_a... | elegantrl/config.py | Apache-2.0 | 9,701 | b2dda559c48996d7b368bb5fe50650f928a285c9 | Python | py | |
import os
import json
from random import random, sample
from copy import deepcopy
import logging
from tqdm import tqdm
import random
import torch
from torch.utils.data import DataLoader, RandomSampler, TensorDataset
from csqa_task.data import ProcessorBase
from rank_task.example import OMCSrankExample
class RankOMC... | CODE/rank_task/data.py | BSD-3-Clause | 3,568 | 29a0665a433cfb59b652a01effe6398030993413 | Python | py | |
from copy import deepcopy
import torch
import torch.nn as nn
import pytorch_lightning as pl
from image.data import ITypeDataModule
"""Standard Module holds all methods we want standard accross models"""
class StandardModule(pl.LightningModule):
def __init__(self, **hparams):
super().__init__()
... | models/standard.py | Apache-2.0 | 5,124 | 10bbce9e119c26317a4987f5a85479c6265a0303 | Python | py | |
import random
import pytest
import torch
from torch.testing import assert_allclose
import numpy as np
import asteroid_filterbanks as fb
from asteroid_filterbanks import transforms
COMPLEX_FBS = [fb.STFTFB, fb.ParamSincFB, fb.AnalyticFreeFB]
@pytest.fixture(scope="module")
def fb_config_list():
keys = ["n_filte... | tests/transforms_test.py | MIT | 8,002 | 1e94ea271adc0e8305f6e2131475e99429b426f2 | Python | py | |
#
# Copyright (c) 2020-2021 The Board of Trustees of the Leland Stanford Junior University
# 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 abov... | genienlp/sts/sts_calculate_scores.py | BSD-3-Clause | 3,514 | 803700f1eb75c9d04bd0f9df1777a658e68b915e | Python | py | |
from typing import Any, Dict, Optional
from pytorch_pfn_extras.training import extension
from pytorch_pfn_extras.training import trigger as trigger_module
from pytorch_pfn_extras.training._manager_protocol import ExtensionsManagerProtocol
from torch.optim.lr_scheduler import ReduceLROnPlateau
def _get_value_from_log... | pytorch_pfn_extras/training/extensions/lr_scheduler.py | MIT | 2,579 | 28be7f758371f9bc35e3836e05134128d7d7101f | Python | py | |
from __future__ import print_function, division
import copy
import os.path as osp
import time
import torch
import torch.nn as nn
import torch.optim as optim
from data_helper import get_dataloaders
from torch.optim import lr_scheduler
from SuperMoon.models import ResNet_HGNN
from SuperMoon.utils import check_dir
dat... | examples/clssification/breast_pathology/train.py | MIT | 3,841 | 424ad3a03ec5522e2006a1bf55f6366cf4d31b31 | Python | py | |
"""
This example loads the pre-trained bert-base-nli-mean-tokens models from the server.
It then fine-tunes this model for some epochs on the STS benchmark dataset.
"""
from torch.utils.data import DataLoader
import math
from sentence_transformers import SentenceTransformer, SentencesDataset, LoggingHandler, losses
fr... | examples/training_stsbenchmark_continue_training.py | Apache-2.0 | 2,797 | 29a148e92a5597f70afd1cb941731a7c5bb04128 | Python | py | |
# -*- coding: utf-8 -*-
# Copyright 2019 Shigeki Karita
# Apache 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
"""Mask module."""
from distutils.version import LooseVersion
import torch
is_torch_1_2_plus = LooseVersion(torch.__version__) >= LooseVersion("1.2.0")
# LooseVersion('1.2.0') == LooseVersion(torch._... | espnet/nets/pytorch_backend/transformer/mask.py | Apache-2.0 | 1,660 | 127f7a200e22674916ae976e045c6eacee81bc1c | Python | py | |
import mmcv
from torch import nn
from .registry import (BACKBONES, NECKS, ROI_EXTRACTORS, SHARED_HEADS, HEADS,
DETECTORS)
def _build_module(cfg, registry, default_args):
assert isinstance(cfg, dict) and 'type' in cfg
assert isinstance(default_args, dict) or default_args is None
arg... | mmdet/models/builder.py | Apache-2.0 | 1,628 | fcdb74eb337079bb70152cbca660f31451217112 | Python | py | |
#!/usr/bin/env python
"""
# Authors: Shengquan Chen, Boheng Zhang, Xiaoyang Chen
# Created Time : Sat 28 Nov 2020 08:31:29 PM CST
# File Name: model.py
# Description:
"""
import numpy as np
import pandas as pd
import pickle
import os
from .loss import *
from .dataset import *
from .utils import *
import torch
from to... | stPlus/model.py | MIT | 8,632 | 29a166d43b4e0a6bf72e7cbc73c6af3552607194 | Python | py | |
from torchvision import transforms
from PIL import Image, ImageDraw, ImageFont
from yolo_models import *
from utils import *
from torch.autograd import Variable
DEVICE = torch.device("cpu")
# Transforms
resize = transforms.Resize((300, 300))
to_tensor = transforms.ToTensor()
normalize = transforms.Normalize(mean=[0... | detect.py | MIT | 6,338 | 29a1688c8e8a877074f021c6bf210bcc07329035 | Python | py | |
import argparse
import random
import sys
import torch
import numpy as np
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("command", type=str, nargs='+', help="Command to run")
parser.add_argument("--seed", type=int, help="Seed of this run", default=1)
args = parser.... | scripts_ufes/set_seed.py | BSD-3-Clause | 573 | 29a17c1807cd2629e30d6fe8df12634baa22f62c | Python | py | |
# coding: utf-8
"""
This modules holds methods for generating predictions from a model.
"""
import os
import sys
import logging
from typing import List, Optional, Tuple
import numpy as np
import torch
from torchtext.data import Dataset, Field
from joeynmt.helpers import bpe_postprocess, load_config, \
get_latest_... | joeynmt/prediction.py | MIT | 24,328 | d7e23c10f0a81c9e2b249828ef19d28b1e90e4b7 | Python | py | |
"""
Copyright 2020 Nvidia Corporation
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Re... | datasets/base_loader.py | BSD-3-Clause | 8,957 | 29a1c9654e10b6e5e3060a006e6d671d21d28438 | Python | py | |
import torch
import torch.nn as nn
import torch.optim as optim
import torch.nn.functional as F
from torch.autograd import Variable
class SimulatorModel(nn.Module):
def __init__(self,
agent_action_size,
hidden_size,
state_size,
user_action_size,
... | src/deep_dialog/usersims/user_model.py | MIT | 1,382 | 29a1d26e9fadbde1cf0804314f104c7dcf1e8553 | Python | py | |
import time
import os
import pandas as pd
import numpy as np
import torch
import torch.nn as nn
import torch.optim as optim
from torchvision import datasets, transforms, models
import json
from PIL import Image
import argparse
from helper import load_checkpoint, process_image, predict, cat_to_name
## TODO: Compl... | predict.py | MIT | 1,984 | 29a203082690789948b6bf7747ea9fb0a65a111c | Python | py | |
import streamlit as st
from PIL import Image
from model import predict
import torch.nn as nn
###################################################################
def accuracy(outputs, labels):
_, preds = torch.max(outputs, dim=1)
return torch.tensor(torch.sum(preds == labels).item() / len(preds))
c... | detector.py | MIT | 3,135 | 29a213dba2d0aeee7c83410cb9c1d708b67ac350 | Python | py | |
from os.path import join
from time import time
from typing import Dict
import torch
import numpy as np
from PIL import Image
from torch.utils.tensorboard import SummaryWriter
class Logger(SummaryWriter):
def __init__(self, *args, logdir='log', **kwargs):
"""Create a summary writer"""
super().__... | ganlib/logger.py | MIT | 1,153 | 1ebe0e3133d7d85735c7db4d4710ba02ee99d361 | Python | py | |
import logging
import os
import json
import numpy as np
import torch
from transformers import BertTokenizer
logger = logging.getLogger(__name__)
class NewsClassifierHandler(object):
"""
NewsClassifierHandler class. This handler takes a review / sentence
and returns the label as either world / sports / bu... | examples/BertNewsClassification/news_classifier_handler.py | Apache-2.0 | 4,228 | 4b4380f59e592f04ae4801f51f5813ab3d136d8c | Python | py | |
import torch
from torch import nn
def calculate_l1_loss(output, target, lagrange_coef=0.0005):
l1_crit = nn.L1Loss(size_average=False) # SmoothL1Loss
reg_loss = l1_crit(output.argmax(dim=1).float(), target.float())
return lagrange_coef * reg_loss
def smooth_in(model):
l_noise = []
... | src/model/utils.py | MIT | 765 | 29a22363e3af69480db0a493461b0c54a8b35a92 | Python | py | |
import math
from torch import nn
from torch.autograd import Function
import torch
import catconv2d_cuda
torch.manual_seed(42)
class CatConvFunction(Function):
@staticmethod
def forward(ctx, input_list, weights, bias, relu):
outputs = catconv2d_cuda.forward(input_list, weights, bias, relu)
va... | catconv2d.py | MIT | 1,633 | 1e204e39fe0cead7b31ad257733e222675b67c61 | Python | py | |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import _init_paths
import os
import os.path as osp
import cv2
import logging
import argparse
import motmetrics as mm
import numpy as np
import torch
from tracker.multitracker import JDETracker
from tracking_ut... | src/track_half.py | MIT | 10,341 | 529d2523d361217bbf7a74b0ad3c3015d6607a62 | Python | py | |
import argparse
import os
import numpy as np
import math
import torchvision.transforms as transforms
from torchvision.utils import save_image
from torch.utils.data import DataLoader
from torchvision import datasets
from torch.autograd import Variable
import torch.nn as nn
import torch.nn.functional as F
import torch... | implementations/lsgan/lsgan.py | MIT | 6,560 | 802d03ad19538ca6331d4eb7fae63bf15b42ede8 | Python | py | |
import torch
from torch.autograd import Variable
import pdb
from dataset import Video
from spatial_transforms import (Compose, Normalize, Scale, CenterCrop, ToTensor)
from temporal_transforms import LoopPadding
def classify_video(video_dir, video_name, class_names, model, opt):
assert opt.mode in ['score', 'feat... | video-classification-3d-cnn-pytorch/classify.py | MIT | 1,555 | 29a249c6442646910c52c27b6ae2f8f9d6e5237d | Python | py | |
# Copyright (c) OpenMMLab. All rights reserved.
import numpy as np
import torch
from mmdet3d.core.points import BasePoints
from mmdet3d.ops.roiaware_pool3d import points_in_boxes_gpu
from .base_box3d import BaseInstance3DBoxes
from .utils import limit_period, rotation_3d_in_axis
class LiDARInstance3DBoxes(BaseInstan... | mmdet3d/core/bbox/structures/lidar_box3d.py | Apache-2.0 | 10,637 | 29a24a16891e2941a2fb8d0fc9c6363a3d930b74 | Python | py | |
#!/usr/bin/env python
# Copyright 2021 Jian Wu
# License: Apache 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
import torch as th
import torch.nn as nn
from aps.asr.base.encoder import EncRetType
from aps.asr.base.attention import padding_mask
from aps.asr.transformer.proj import get_xfmr_proj
from aps.asr.transf... | aps/streaming_asr/transformer/encoder.py | Apache-2.0 | 4,298 | 29a26c0c6e9f0fa7d1f2ed26397ef83960bf865d | Python | py | |
import torch
from torch.autograd import Function, Variable
class DiceCoeff(Function):
"""Dice coeff for individual examples"""
def forward(self, input, target):
self.save_for_backward(input, target)
self.inter = torch.dot(input.view(-1), target.view(-1)) + 0.0001
self.union = torch.sum... | utilities/other_utils/Unet_implementations/Pytorch-UNet/dice_loss.py | MIT | 1,214 | 29a287d5ffbab25417acb1c502d8c98b0ff62195 | Python | py | |
import torch
import os
import glob
import tqdm
from torch.nn.utils import clip_grad_norm_
def train_one_epoch(model, optimizer, train_loader, model_func, lr_scheduler, accumulated_iter, optim_cfg,
rank, tbar, tb_log=None, leave_pbar=False):
dataloader_iter = iter(train_loader)
total_it_eac... | tools/train_utils/train_utils.py | Apache-2.0 | 5,023 | a981e41b018e697cea3d9ea1adca063b3609e9e5 | Python | py | |
"""
Evaluates a stored snapshot on the valid or test partition. Performance is measured in micro-F1 score.
Usage: python -m scripts.evaluate {model} {run_id} {snapshot_iteration} {partition}
The actual language is inferred from the trained model.
"""
from argparse import ArgumentParser
import torch
from torch.utils.d... | scripts/evaluate.py | MIT | 8,562 | 7c45899944d366d09e3a4347fd8e14ea6c893e3e | 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 examples.simultaneous_translation.utils.latency import LatencyInference
import argparse
import torch
import json
LATENCY_METRICS = [
... | examples/simultaneous_translation/eval/eval_latency.py | MIT | 2,432 | 12cfaa4ed16befae41f993c284f3766979a24b14 | Python | py | |
# Original referece: https://github.com/janfreyberg/pytorch-revgrad
# Only weight paramter is added.
import torch
class Func(torch.autograd.Function):
@staticmethod
def forward(ctx, input_, weight):
ctx.save_for_backward(input_)
ctx.weight = weight
output = input_
return outpu... | Gradient_Reversal_Layer.py | MIT | 996 | fcc714a17b82a0aa0515915fdd98364c8a072d6b | Python | py | |
import torch.nn as nn
import torch.nn.functional as F
import torch
from lovász_loss import lovasz_hinge, binary_xloss
################### DICE ########################
def IoU(logit, truth, smooth=1):
prob = torch.sigmoid(logit)
intersection = torch.sum(prob * truth)
union = torch.sum(prob + truth)
iou ... | Loss.py | MIT | 3,521 | f9bdec8b89d6e28f8e71093984070b516462ce57 | Python | py | |
import torch
from torch import nn
from torchvision.models import mobilenet_v2
from torch_tools.models.util import Lambda
class MobileNetFeatures(nn.Module):
@classmethod
def load_pretrained(cls, **kwargs):
return cls(mobilenet_v2(pretrained=True), **kwargs)
def __init__(self, trained_net, log=Fa... | torch_tools/models/vision/feature_extractors/mobilenets.py | MIT | 2,129 | 29a2c98828dd9576a7761f1ab97a2d42e55a47b8 | Python | py | |
from taichi.core.util import ti_core as _ti_core
from taichi.lang import impl
from taichi.lang.util import python_scope, to_numpy_type, to_pytorch_type
import taichi as ti
class Field:
"""Taichi field with SNode implementation.
A field is constructed by a list of field members.
For example, a scalar fie... | python/taichi/lang/field.py | MIT | 8,602 | 29a2d11de19c3b58d9515c96df188be2ee0fdc35 | Python | py | |
import random
import math
import torch
from torch import nn, Tensor
import torchvision
from torch.jit.annotations import List, Tuple, Dict, Optional
from torchvision.ops import misc as misc_nn_ops
from .image_list import ImageList
from .roi_heads import paste_masks_in_image
@torch.jit.unused
def _resize_image_and_ma... | torchvision/models/detection/transform.py | BSD-3-Clause | 11,537 | 29a2e07d5a2010ecfb8f58352363ab97d5dfd081 | Python | py | |
import torch
import torch.nn as nn
from torch.nn import functional as F
class Autoencoder(nn.Module):
def __init__(self, input_size, hidden_size):
"""
General Autoencoder. Takes in as input Encoder and Decoder layers.
:param encoder: something that's nn.Module
:param decoder: somet... | model.py | MIT | 4,892 | 651ccd90bfb9f5b9b5dcfd123725ba002474962f | Python | py | |
import numpy as np
from numpy.lib.utils import source
import pandas as pd
import torch
import librosa
import soundfile
from icecream import ic
from utils import check_type, extract_audio, mono_load
from config import InferenceConfig as IC
from csrc.configurations import DatasetConfig as DC
from csrc.configurations imp... | inferer.py | Apache-2.0 | 8,288 | 7c7889b15c34046d0e87d43fa2288dd3dec5174f | Python | py | |
from typing import List, Tuple
import torch
import torch.nn.functional as F
import numpy as np
import gc
from pathlib import Path
from ..core import Regressor, DataDict, Data
class NNModel(Regressor):
def __init__(self, model,
optimizer,
loss_func,
**kwargs) -> ... | potok/vision/TorchNNModel.py | Apache-2.0 | 2,710 | fd698aa3bc027d1c3ea5293eb724c4958f3d416e | Python | py | |
import gym
import torch as th
import numpy as np
import torch.nn as nn
import torch.nn.functional as F
lr = 0.001
gamma = 0.9
hidden = 32
env = gym.make('CartPole-v0')
device = "cpu"
env = env.unwrapped
n_action = env.action_space.n
n_state = env.observation_space.shape[0]
class actor(nn.Module): # policy net
d... | AC/ac_work.py | MIT | 2,892 | 5ec90b8b304775bf75b76812b8f5f732f1ff3512 | Python | py | |
import torch
from typing import Optional, List
from torch import Tensor
import torchvision
def collate_fn(batch):
batch = list(zip(*batch))
batch[0] = nested_tensor_from_tensor_list(batch[0])
return tuple(batch)
def _max_by_axis(the_list):
# type: (List[List[int]]) -> List[int]
maxes = the_list[0... | utils.py | MIT | 2,747 | 29a3241386a215fc05d94f059a745164e995718d | Python | py | |
# @Time : 2020/10/21
# @Author : Kaiyuan Li
# @email : tsotfsk@outlook.com
# UPDATE
# @Time : 2020/10/21, 2021/8/29
# @Author : Kaiyuan Li, Zhichao Feng
# @email : tsotfsk@outlook.com, fzcbupt@gmail.com
# UPDATE:
# @Time : 2021/12
# @Author : Yong Zheng
# @Notes : made light changes to adapt it for CARS
"""... | deepcarskit/evaluator/base_metric.py | MIT | 4,760 | 29a328ca7f4cf7504903e08746845b0b8a7287a5 | Python | py | |
import numpy as np
import pandas as pd
import pickle, os, csv, math, time, joblib
from sklearn.ensemble import ExtraTreesRegressor, ExtraTreesClassifier
from lightgbm import LGBMRegressor, LGBMClassifier
from sklearn.metrics import mean_absolute_error
from sklearn.linear_model import LinearRegression, LogisticRegressio... | simulated_fqi/models/fqi.py | MIT | 12,271 | 802746fbdfb3589d4e45fba66ec87e20ebab064e | Python | py | |
# This code is part of Qiskit.
#
# (C) Copyright IBM 2021.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative wo... | qiskit_machine_learning/connectors/torch_connector.py | Apache-2.0 | 11,318 | 24b863629b659858e202a8659e3dd474b46c8339 | Python | py | |
import cPickle as pickle
import string
import sys
import time
from itertools import izip
import numpy as np
from datetime import datetime, timedelta
import buffering
import utils
import logger
from configuration import config, set_configuration
import pathfinder
import app
import torch
from torch.autograd import Va... | train.py | MIT | 8,588 | dfaba174fb56b80019ae2c7fec56002884e9368d | Python | py | |
import math
import torch
from torch import nn
from utee import act
from torch.autograd import Variable
from collections import OrderedDict
import numpy as np
def compute_integral_part(in_act, overflow_rate):
abs_value = in_act.abs().view(-1)
sorted_value = abs_value.sort(dim=0, descending=True)[0]
split_i... | scripts/nn/utee/compress.py | MIT | 6,883 | 5f15b03abdc86c6b7e5145123c7a4dcab27afd97 | Python | py | |
from torch import nn
import torch
import torch.nn.functional as F
from .util import AntiAliasInterpolation2d, make_coordinate_grid
from torchvision import models
import numpy as np
from torch.autograd import grad
class Vgg19(torch.nn.Module):
"""
Vgg19 network for perceptual loss. See Sec 3.3.
"""
def... | cogs/deep/modules/model.py | MIT | 11,331 | 29a3a44cb5455a6c930050553e4e1ebd15c4f564 | Python | py | |
import torch
import torch.nn as nn
import torch.nn.functional as F
from torchvision import models
from monodepth.models.blocks import Interpolate
class _ASPPModule(nn.Module):
def __init__(self, inplanes, planes, kernel_size, padding, dilation):
super(_ASPPModule, self).__init__()
self.conv1 = n... | nasws/cnn/search_space/monodepth/models/planar_net.py | MIT | 6,923 | d70a4cd0cd131a53a60501a1f427eacd4401b7ac | Python | py | |
"""
code by Tae Hwan Jung(Jeff Jung) @graykode
code reference : https://github.com/pytorch/pytorch/issues/2001,
https://gist.github.com/HTLife/b6640af9d6e7d765411f8aa9aa94b837,
https://github.com/sksq96/pytorch-summary
Inspired by https://github.com/sksq... | modelsummary/modelsummary.py | MIT | 4,891 | e975d219ecb3f899c6eff57825b2547dd58d6e6e | Python | py | |
"""
pytoch/caffe2 backend via onnx
https://pytorch.org/docs/stable/onnx.html
FIXME: this currently does not work for our resnet50.onnx model
caffe2 complains about the following:
[E ../caffe2/core/operator_schema.cc:64] Input index 3
(resnet_model/batch_normalization/moving_mean:0) and output idx 1
(resnet_model/bat... | cloud/image_classification/python/backend_pytorch.py | Apache-2.0 | 2,763 | 29a3c6ddeb20118fd0501aabe54976d969169d06 | Python | py | |
import pickle
import sys
import timeit
import os
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
import itertools
import pandas as pd
#from sklearn.metrics import roc_auc_score, precision_score, recall_score
class GraphNeuralNetwork(nn.Module):
def __init__(self):
... | run_test.py | Apache-1.1 | 8,076 | 104499922c7e9ab2528f8b5556a48e13042431a4 | Python | py | |
# Copyright (c) 2021, NVIDIA CORPORATION & AFFILIATES. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this sof... | training/loss.py | MIT | 8,268 | 3406217bb0b62a33c2ec48c6353aff6e4a508978 | Python | py | |
import random
from collections.abc import Sequence
import mmcv
import numpy as np
from numpy import random as npr
from PIL import Image, ImageFilter
from skimage.util import view_as_windows
from torch.nn.modules.utils import _pair
from torchvision.transforms import ColorJitter as _ColorJitter
from torchvision.transfor... | mmaction/datasets/pipelines/augmentations.py | Apache-2.0 | 60,630 | 29a3e891d2449b40633f854a5791e9fef666f017 | Python | py | |
from __future__ import division
import torch
import torch.nn as nn
import torch.nn.functional as F
from .basemodel import BaseModel
from .tcn import TemporalConvNet
from utils.net_util import norm_col_init, weights_init
from .model_io import ModelOutput
class SAVN(BaseModel):
def __init__(self, args):
su... | models/savn.py | Apache-2.0 | 7,260 | b24cf9a46ea7708e24c6ab7ad3c473e0a4e4b648 | Python | py | |
import abc
import torch.nn
import itertools
from typing import Optional, Tuple, Union
__all__ = ["Manifold", "ScalingInfo"]
class ScalingInfo(object):
"""
Scaling info for each argument that requires rescaling.
.. code:: python
scaled_value = value * scaling ** power if power != 0 else value
... | geoopt/manifolds/base.py | Apache-2.0 | 29,079 | 29a40c13ee18e22d3067ac7624dc395067f8fdf7 | Python | py | |
import math
import torch
import torch.nn as nn
import torch.nn.functional as F
from layers.cat_cond_bn import CatCondBatchNorm2d
def _upsample(x):
h, w = x.shape[2:]
return F.upsample(x, size=(h * 2, w * 2))
def upsample_conv(x, conv):
return conv(_upsample(x))
class Block(nn.Module):
def __init__(s... | gen_models/resblocks.py | MIT | 2,290 | 1e60cb6c6dab02c0dc7e079aa005805870d83f65 | Python | py | |
import random
import math
import pyclick
import torch
import torch.nn.functional as F
import time
import pickle
import bz2
import _pickle as cPickle
import models
import utils.noise
import utils.screen
import utils.OCR
import utils.info_plot
import utils.schedule
import utils.checkpoint
from memory import ReplayMemory... | trainer.py | MIT | 20,549 | 45a57a8dde563f45c6020811edd8adb351fa5759 | Python | py | |
import torch
import torch.nn as nn
import torch.nn.functional as F
class DoubleConv(nn.Module):
def __init__(self, in_channels, out_channels, mid_channels=None):
super().__init__()
if not mid_channels:
mid_channels = out_channels
self.double_conv = nn.Sequential(
nn.C... | medimodule/Brain/mri_bet/models/Unet.py | Apache-2.0 | 3,143 | f9c4a25197dcda1c5a4baec53b50823c5b012a06 | Python | py | |
# Importing Required Libraries
import numpy as np
import torch
import torch.nn as nn
import torch.optim as optim
import torchvision
import torchvision.models as models
import torchvision.transforms as transforms
import copy
import argparse
import os
import logging
import sys
from tqdm import tqdm
from PIL import Image... | model_train.py | MIT | 8,434 | 1e5ca7a97d1b4c8890d59245b087b1bc7187e440 | Python | py | |
# coding=utf-8
# Copyright (c) 2019, Facebook, Inc. and its affiliates. All Rights Reserved
# Copyright 2018 The Google AI Language Team Authors and The HuggingFace Inc. 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... | tutorials/downstream_tutorial/spanbert_model/pytorch_pretrained_bert/optimization.py | Apache-2.0 | 8,534 | ff42ec7afd5f98cb9b533d1ff8c35af81fc3931b | Python | py | |
import time
import torch
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.patches as patches
def boxes_iou(box1, box2):
# Get the Width and Height of each bounding box
width_box1 = box1[2]
height_box1 = box1[3]
width_box2 = box2[2]
height_box2 = box2[3]
# Calculate ... | src/Notebooks/YOLO/YOLO_utils.py | MIT | 10,021 | 29a44469a09b0891bb2bb3007b92dede8c5f042d | Python | py | |
# coding=utf-8
# Copyright 2018 the HuggingFace Inc. 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... | tests/trainer/test_trainer.py | Apache-2.0 | 98,932 | 4bae763cc4e8e6b5140f801849c41d2e8b7700f1 | Python | py | |
import torch
import numpy as np
from typing import Dict, Any
import math
import gym
from haco.DIDrive_core.envs import CarlaEnvWrapper, BenchmarkEnvWrapper
from ding.torch_utils.data_helper import to_ndarray
DEFAULT_ACC_LIST = [
(0, 1),
(0.25, 0),
(0.75, 0),
]
DEFAULT_STEER_LIST = [
-0.8,
-0.5,
... | haco/DIDrive_core/demo/simple_rl/env_wrapper.py | Apache-2.0 | 4,477 | 29a485e93e89d281d1bdac7a128ac1a2ae831057 | Python | py | |
#!/usr/bin/env python
import argparse
import numpy as np
import torch
import torch.nn as nn
import torch.optim as optim
import pickle as pk
from discriminator import Discriminator
from generator import Generator
from utils import load_dataset
from logger_utils import Logger
from emittance_logger_utils im... | GAN/gan.py | MIT | 18,196 | 29a490c28257d40cfe1de68b79dd2f6db010ce6a | Python | py | |
from collections import OrderedDict
import torch
from apex.optimizers import FusedAdam
from apex.contrib.sparsity import ASP
def build_model(args):
od = OrderedDict()
for i in range(args.num_layers):
if i == 0:
od['linear_layer_%d' % (i+1)] = torch.nn.Linear(args.input_features, args.hidde... | apex/contrib/sparsity/test/checkpointing_test_part1.py | BSD-3-Clause | 3,358 | 34232b8295fb09ca0b903e0cec46d917b02f126b | Python | py | |
import os
import argparse
import tqdm
import json
import re
import torch
from torch import nn
from torch.autograd import Variable
from torch.utils.data import DataLoader
from torchvision import transforms
import numpy as np
from tensorboardX import SummaryWriter
import torch.optim as optim
import torch.optim.lr_schedul... | few-shot/main.py | MIT | 8,949 | 29a4b113b1e8f2d03b8d30ae802d66782bf7ed41 | Python | py | |
import numpy as np
import torch
import torch.nn as nn
from ...utils import box_coder_utils, common_utils, loss_utils
from .target_assigner.anchor_generator import AnchorGenerator
from .target_assigner.atss_target_assigner import ATSSTargetAssigner
from .target_assigner.axis_aligned_target_assigner import AxisAlignedTa... | pcdet/models/dense_heads/anchor_head_template.py | Apache-2.0 | 12,801 | 29a4b8f7b68386f0adc9330649cb411868793d36 | Python | py | |
from pytracking.tracker.base import BaseTracker
import torch
import torch.nn.functional as F
import torch.nn
import math
import time
from pytracking import dcf, fourier, TensorList, operation
from pytracking.features.preprocessing import numpy_to_torch
from pytracking.utils.plotting import show_tensor
from pytracking.l... | fenetpp/pytracking/tracker/atom/atom.py | MIT | 40,960 | 29a507c91f9fbc6563fe6808edb6c568982a193c | Python | py | |
from sentence_transformers.evaluation import SentenceEvaluator
from sentence_transformers.util import batch_to_device
from sentence_transformers import SentenceTransformer
from typing import List, Tuple, Dict
import torch
import numpy as np
import logging
import os
import csv
try:
import wandb
wandb_available... | sentence_transformers/evaluation/MSEEvaluatorFromDataFrame.py | Apache-2.0 | 4,199 | 4589c3eb16f43dd94cd5901cd04b3fa331a56e9a | Python | py | |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import *
import misc.utils as utils
import pdb
class CaptionModel(nn.Module):
def __init__(self, opt):
super(C... | models/CaptionModel.py | MIT | 8,989 | 45f7f8bbf124f37a4a8d2c74ea528cf036887c1b | Python | py | |
from __future__ import division
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Variable
import numpy as np
import cv2
def unique(tensor):
"""Can be multiple true detections of the same class."""
tensor_np = tensor.cpu().numpy()
unique_np = np.unique(tensor_n... | notes/reference/tutorials/yolo-in-pytorch/util.py | MIT | 6,924 | a91bbd5b58ece62860349dba4d1fa84048b5b3f0 | Python | py | |
# YOLOv5 general utils
import contextlib
import glob
import logging
import os
import platform
import random
import re
import signal
import time
import urllib
from itertools import repeat
from multiprocessing.pool import ThreadPool
from pathlib import Path
from subprocess import check_output
import cv2
import math
imp... | utils/general.py | MIT | 28,297 | 52b0f3203a36e5e2326096b7d5234cc603bee214 | Python | py | |
import ast
import logging
import re
from collections import defaultdict
from typing import Dict, List, Sequence, Tuple, Union
from torch import nn
from meddlr.modeling.layers.build import get_layer_kind
from meddlr.utils.registry import Registry
META_ARCH_REGISTRY = Registry("META_ARCH") # noqa F401 isort:skip
META... | meddlr/modeling/meta_arch/build.py | Apache-2.0 | 7,326 | 28f0fbb9e21b59ce636115b09b46c5d0be73ec77 | Python | py | |
# -*- coding: utf-8 -*-
"""
Created on Thu Sep 12 13:37:37 2019 by Attila Lengyel - attila@lengyel.nl
Write this
"""
import torch
import torch.nn as nn
import torch.optim as optim
import torch.backends.cudnn as cudnn
import torchvision.transforms.functional as TF
import time
import os
import cv2
im... | semantic-segmentation/baseline.py | BSD-3-Clause | 22,547 | 5e505fcef7b2f9f5c9d68e3a0e92004b76231b80 | Python | py | |
import matplotlib.pyplot as plt
import torch
import numpy as np
def valid(data):
if data is None:
return False
if data.x is None:
return False
if data.x.shape[1] == 0:
return False
return True
def generate_histc(dataset):
ini_val = np.float64(0.0)
num_pairs = []
pos... | utils.py | MIT | 1,788 | 29a5bce55dde456408388db0fd050568e114164c | Python | py | |
import argparse
import numpy as np
import torch
import torch.backends.cudnn as cudnn
import torchvision.transforms as transforms
from torch import nn
from torch.utils.tensorboard import SummaryWriter
from config import device, print_freq, num_workers, grad_clip, root, filelists_train, param_fp_train, filelists_val, \... | train.py | MIT | 7,117 | b211272ccf6ba7dd27683f89837e74576c44a849 | 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_mlm_no_trainer.py | Apache-2.0 | 28,741 | d7d8d011ac8710bb98b06fd3dc8f22e00749f082 | Python | py | |
import torch
from torch import nn
from torch.nn import functional as F
from .utils import (
round_filters,
round_repeats,
drop_connect,
get_same_padding_conv2d,
get_model_params,
efficientnet_params,
load_pretrained_weights,
Swish,
MemoryEfficientSwish,
)
class MBConvBlock(nn.Modul... | efficientnet_pytorch/model.py | Apache-2.0 | 10,047 | 706ebb938ac09926f92e19af53fa371c943cafc5 | Python | py | |
# --------------------------------------------------------
# Pytorch Faster R-CNN
# Licensed under The MIT License [see LICENSE for details]
# Written by Ruotian Luo & Licheng Yu
# --------------------------------------------------------
from __future__ import absolute_import
from __future__ import division
from __futu... | lib/nets/network.py | MIT | 28,090 | 29a5fdb88aaea576b8a812d27425a93634e46da2 | Python | py | |
#!/usr/bin/env python3
r"""
Abstract base module for all botorch acquisition functions.
"""
from abc import ABC, abstractmethod
from torch import Tensor
from torch.nn import Module
from ..models.model import Model
class AcquisitionFunction(Module, ABC):
r"""Abstract base class for acquisition functions."""
... | botorch/acquisition/acquisition.py | MIT | 991 | 29a6186cefb0378bac04c83c152fcf454c8bb5fb | Python | py | |
# coding: UTF-8
import time
import torch
import numpy as np
from train_eval import train, init_network
from importlib import import_module
import argparse
parser = argparse.ArgumentParser(description='Chinese Text Classification')
parser.add_argument('--model', type=str, default="TextCNN", help='choose a model: TextCN... | run.py | MIT | 2,251 | a9764ff792e3fb92038be9ab8dd6fdee843e389f | Python | py | |
import torch
import torch.autograd as autograd
import torch.nn as nn
def protected_max(x, dim):
return torch.max(x, dim=dim)[0]
def count_parameters(model):
return sum(p.numel() for p in model.parameters() if p.requires_grad)
class ModelWarper(nn.Module):
def __init__(self, layers):
super(Model... | exps/deep_learning/models.py | MIT | 9,775 | 1065d26e6a839abe645e6f8119bca20026e9159a | Python | py | |
#
# Copyright (c) 2018 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... | distiller/quantization/range_linear.py | Apache-2.0 | 74,759 | 29a639b31f1332d44f06bb02a76ba14dbbb54b7a | Python | py | |
import torch
def save_checkpoint(net, optimizer, epoch, estimators, checkpoint_name):
save_dict = {"model": net.module.state_dict(),
"optimizer": optimizer.state_dict(),
# The epoch would be immediately incremented after saving, so save next epoch
"epoch": epoch + 1}
if estimators:... | codebase/utils/cluster/utils.py | MIT | 1,375 | dfcb961fa82a5c294ac7375386500af3170bcae8 | Python | py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.