repo stringlengths 1 99 | file stringlengths 13 215 | code stringlengths 12 59.2M | file_length int64 12 59.2M | avg_line_length float64 3.82 1.48M | max_line_length int64 12 2.51M | extension_type stringclasses 1
value |
|---|---|---|---|---|---|---|
alf-pytorch | alf-pytorch/alf/environments/metadrive/extra_rewards.py | # Copyright (c) 2022 Horizon Robotics and ALF Contributors. 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... | 12,130 | 31.786486 | 90 | py |
alf-pytorch | alf-pytorch/alf/environments/metadrive/agent_perception.py | # Copyright (c) 2022 Horizon Robotics and ALF Contributors. 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... | 10,327 | 40.14741 | 87 | py |
alf-pytorch | alf-pytorch/alf/trainers/policy_trainer.py | # Copyright (c) 2019 Horizon Robotics. 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 applicab... | 45,492 | 39.691413 | 106 | py |
alf-pytorch | alf-pytorch/alf/trainers/evaluator.py | # Copyright (c) 2022 Horizon Robotics and ALF Contributors. 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... | 13,118 | 38.996951 | 102 | py |
alf-pytorch | alf-pytorch/alf/trainers/policy_trainer_test.py | # Copyright (c) 2020 Horizon Robotics and ALF Contributors. 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... | 4,522 | 35.772358 | 80 | py |
smpy | smpy-master/doc/conf.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# smpy documentation build configuration file, created by
# sphinx-quickstart on Tue Apr 14 10:29:06 2015.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in this
# autog... | 8,793 | 30.633094 | 79 | py |
HPMN | HPMN-master/code/srnn.py | import cPickle as pkl
import os
import random
import tensorflow as tf
from keras.layers import GRU
from sklearn.metrics import *
import math
from data_loader import *
from ntm_cell import NTMCell
# CROP_PKL_PATH = '../../data/amazon/Books/dataset_crop.pkl'
CROP_PKL_PATH = '../../data/taobao/dataset_crop.pkl'
# PADDI... | 97,007 | 45.886419 | 149 | py |
MINE | MINE-main/synthesis_task.py | import os
import glob
import lpips
import torch
import torchvision
import torch.nn as nn
import torch.optim as optim
import torch.distributed as dist
from torch.nn.parallel import DistributedDataParallel as DDP
from utils import restore_model
from utils import run_shell_cmd
from utils import get_embedder
from utils ... | 31,385 | 45.774963 | 129 | py |
MINE | MINE-main/utils.py | import torch
import os
import subprocess
def disparity_normalization_vis(disparity):
"""
:param disparity: Bx1xHxW, pytorch tensor of float32
:return:
"""
assert len(disparity.size()) == 4 and disparity.size(1) == 1
disp_min = torch.amin(disparity, (1, 2, 3), keepdim=True)
disp_max = torc... | 6,692 | 30.130233 | 100 | py |
MINE | MINE-main/train.py | import os
import sys
import argparse
import yaml
import json
import shutil
import numpy as np
import torch
from torch.utils.data import DataLoader
import torch.distributed as dist
from torch.utils.tensorboard import SummaryWriter
from synthesis_task import SynthesisTask
from utils import run_shell_cmd
parser = argp... | 6,121 | 37.2625 | 101 | py |
MINE | MINE-main/network/ssim.py | import torch
import torch.nn.functional as F
from torch.autograd import Variable
from math import exp
def gaussian(window_size, sigma):
gauss = torch.Tensor([exp(-(x - window_size//2)**2/float(2*sigma**2)) for x in range(window_size)])
return gauss/gauss.sum()
def create_window(window_size, channel):
_1... | 2,558 | 32.233766 | 104 | py |
MINE | MINE-main/network/layers.py | import torch
import torch.nn as nn
import torch.nn.functional as F
import torchvision
from kornia.filters import spatial_gradient
class VGGPerceptualLoss(torch.nn.Module):
def __init__(self, resize=True):
super(VGGPerceptualLoss, self).__init__()
blocks = []
blocks.append(torchvision.mode... | 4,024 | 39.25 | 96 | py |
MINE | MINE-main/network/monodepth2/resnet_encoder.py | # Copyright Niantic 2019. Patent Pending. All rights reserved.
#
# This software is licensed under the terms of the Monodepth2 licence
# which allows for non-commercial use only, the full terms of which are made
# available in the LICENSE file.
from __future__ import absolute_import, division, print_function
import n... | 4,565 | 40.889908 | 111 | py |
MINE | MINE-main/network/monodepth2/depth_decoder.py | # Copyright Niantic 2019. Patent Pending. All rights reserved.
#
# This software is licensed under the terms of the Monodepth2 licence
# which allows for non-commercial use only, the full terms of which are made
# available in the LICENSE file.
from __future__ import absolute_import, division, print_function
import n... | 6,145 | 40.248322 | 114 | py |
MINE | MINE-main/network/monodepth2/layers.py | # Copyright Niantic 2019. Patent Pending. All rights reserved.
#
# This software is licensed under the terms of the Monodepth2 licence
# which allows for non-commercial use only, the full terms of which are made
# available in the LICENSE file.
from __future__ import absolute_import, division, print_function
import n... | 8,229 | 29.257353 | 93 | py |
MINE | MINE-main/network/monodepth2/view_dependent_radiance_predictor.py | import torch
import torch.nn as nn
import torch.nn.functional as F
def conv(in_planes, out_planes, kernel_size):
m = nn.Sequential(
nn.Conv2d(in_planes, out_planes, kernel_size=kernel_size,
stride=1, padding=(kernel_size - 1) // 2, bias=False),
nn.BatchNorm2d(out_planes),
... | 1,483 | 31.26087 | 89 | py |
MINE | MINE-main/visualizations/image_to_video.py | import numpy as np
import cv2
import time
import yaml
import sys
from scipy.interpolate import interp1d
import os
import argparse
import logging
import math
import torch
import json
from tqdm import tqdm
from moviepy.editor import ImageSequenceClip
from torch.utils.tensorboard import SummaryWriter
from synthesis_task ... | 13,403 | 41.150943 | 122 | py |
MINE | MINE-main/input_pipelines/llff/nerf_dataset.py | import random
import os
import numpy as np
from PIL import Image
from collections import defaultdict
import torch
from torch.utils.data.dataloader import default_collate
import torchvision.transforms as transforms
import torch.utils.data as data
from input_pipelines import colmap_utils
def _collate_fn(batch):
_... | 10,341 | 38.323194 | 98 | py |
MINE | MINE-main/operations/test_rendering.py | import torch
import numpy as np
import cv2
import matplotlib.pyplot as plt
from scipy.spatial.transform import Rotation
from operations import mpi_rendering
from operations.homography_sampler import HomographySample
def test_mpi_composition():
B = 1
car_np = cv2.imread('/data00/home/jiaxinli/repos/ad-img-to-... | 3,797 | 33.216216 | 120 | py |
MINE | MINE-main/operations/mpi_rendering.py | import torch
from operations.homography_sampler import HomographySample
from operations.rendering_utils import transform_G_xyz, sample_pdf, gather_pixel_by_pxpy
def render(rgb_BS3HW, sigma_BS1HW, xyz_BS3HW, use_alpha=False, is_bg_depth_inf=False):
if not use_alpha:
imgs_syn, depth_syn, blend_weights, wei... | 11,631 | 41.764706 | 116 | py |
MINE | MINE-main/operations/homography_sampler.py | import torch
import numpy as np
import cv2
import matplotlib.pyplot as plt
from scipy.spatial.transform import Rotation
from utils import inverse
class HomographySample:
def __init__(self, H_tgt, W_tgt, device=None):
if device is None:
self.device = torch.device("cpu")
else:
... | 8,321 | 42.34375 | 131 | py |
MINE | MINE-main/operations/rendering_utils.py | import torch
import torch.nn.functional as F
def transform_G_xyz(G, xyz, is_return_homo=False):
"""
:param G: Bx4x4
:param xyz: Bx3xN
:return:
"""
assert len(G.size()) == len(xyz.size())
if len(G.size()) == 2:
G_B44 = G.unsqueeze(0)
xyz_B3N = xyz.unsqueeze(0)
else:
... | 5,531 | 38.234043 | 115 | py |
ppmd | ppmd-master/doc/conf.py | # -*- coding: utf-8 -*-
#
# ppmd documentation build configuration file, created by
# sphinx-quickstart on Tue Sep 8 10:16:56 2015.
#
# This file is execfile()d with the current directory set to its containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All co... | 7,928 | 30.843373 | 88 | py |
beiwe-backend | beiwe-backend-main/config/jinja2.py | """ Original Document sourced from
https://samuh.medium.com/using-jinja2-with-django-1-8-onwards-9c58fe1204dc """
from datetime import date
from django.contrib.staticfiles.storage import staticfiles_storage
from django.urls import reverse
from jinja2 import Environment
from config.settings import SENTRY_JAVASCRIPT_... | 4,862 | 51.858696 | 154 | py |
LAS | LAS-master/source/conf.py | # -*- coding: utf-8 -*-
#
# LAS documentation build configuration file, created by
# sphinx-quickstart on Tue Feb 7 14:10:03 2017.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All c... | 8,186 | 28.663043 | 125 | py |
detect-gpt | detect-gpt-main/run.py | import matplotlib.pyplot as plt
import numpy as np
import datasets
import transformers
import re
import torch
import torch.nn.functional as F
import tqdm
import random
from sklearn.metrics import roc_curve, precision_recall_curve, auc
import argparse
import datetime
import os
import json
import functools
import custom_... | 40,079 | 41.683706 | 269 | py |
UID | UID-main/code/save_traj.py | from my_utils import *
from args_parser import *
from core.agent import Agent
from core.dqn import *
from core.ac import *
import h5py
from numpy.linalg import norm
from itertools import count
p_color = "yellow"
print_color = p_color
""" Load policy model file from pt file (pytorch model), replay policy, and save tra... | 7,139 | 38.016393 | 137 | py |
UID | UID-main/code/rl_main.py | from my_utils import *
from args_parser import *
from core.agent import Agent
from core.dqn import *
from core.ac import *
""" The main entry function for RL """
def main(args):
if use_gpu:
torch.backends.cudnn.deterministic = True
print(colored("Using CUDA.", p_color))
torch.cuda.manual_s... | 8,977 | 45.278351 | 145 | py |
UID | UID-main/code/trex_main.py | from my_utils import *
from args_parser import *
from core.agent import Agent
from core.ac import *
from core.irl import *
import torch.nn as nn
from tqdm import tqdm
class Net(nn.Module):
def __init__(self, args, state_dim, action_dim, hidden_size=256):
super(Net, self).__init__()
self.cuda = a... | 22,382 | 38.268421 | 135 | py |
UID | UID-main/code/uid_main.py | from my_utils import *
from args_parser import *
from core.agent import Agent
from core.dqn import *
from core.ac import *
from core.irl import *
from tensorboardX import SummaryWriter
from tqdm import tqdm
import math
""" The main entry function for RL """
def main(args):
if args.il_method is None:
meth... | 15,147 | 46.485893 | 170 | py |
UID | UID-main/code/core/ac.py | from my_utils import *
from core_nn.nn_ac import *
""" Basic Actor-Critic with GAE. This is not A2C, since the networks are updated in an epoch style like PPO """
class AC():
def __init__(self, state_dim, action_dim, args, a_bound=1, encode_dim=0):
self.state_dim = state_dim + encode_dim
self.acti... | 23,299 | 49.542299 | 231 | py |
UID | UID-main/code/core/dqn.py | from my_utils import *
from core_nn.nn_ac import *
""" DQN and Double DQN """
class DQN():
def __init__(self, state_dim, action_num, args, double_q=False, encode_dim=0):
self.state_dim = state_dim + encode_dim
self.action_num = action_num
self.gamma = args.gamma
self.double_q = d... | 9,493 | 52.039106 | 187 | py |
UID | UID-main/code/core/bc.py | from my_utils import *
from core_nn.nn_ac import Policy_Gaussian
from core_nn.nn_irl import *
from core.irl_pre import IRL #
import h5py
""" Behavior cloning. Standard least-square regression gradient steps. """
class BC(IRL): # extend IRL to get demonstrations-related functions
def __init__(self, state_dim... | 5,220 | 44.008621 | 219 | py |
UID | UID-main/code/core/agent.py | from my_utils import *
class Agent:
def __init__(self, env, render=0, clip=False, t_max=1000, test_cpu=True):
self.env = env
self.render = render
self.test_cpu = test_cpu
self.t_max = t_max
self.is_disc_action = len(env.action_space.shape) == 0
def collect_sample... | 4,207 | 29.715328 | 114 | py |
UID | UID-main/code/core/irl.py | from my_utils import *
from core_nn.nn_irl import *
# from core_nn.nn_old import *
import h5py
import torch
""" MaxEnt-IRL. I.e., Adversarial IL with linear loss function. """
class IRL():
def __init__(self, state_dim, action_dim, args, initialize_net=True, rebuttal=False):
self.mini_batch_size = args.mini_... | 31,981 | 41.871314 | 121 | py |
UID | UID-main/code/core_nn/nn_irl.py | from my_utils import *
class Discriminator(nn.Module):
def __init__(self, state_dim, action_dim, num_outputs=1, hidden_size=(100, 100), activation='tanh', normalization=None, clip=0):
super().__init__()
if activation == 'tanh':
self.activation = torch.tanh
elif activation == 're... | 8,062 | 37.395238 | 148 | py |
UID | UID-main/code/core_nn/nn_ac.py | from my_utils import *
class Policy_Gaussian(nn.Module):
def __init__(self, state_dim, action_dim, hidden_size=(100, 100), activation='tanh', param_std=1, log_std=0, a_bound=1, tanh_mean=1, squash_action=1):
super().__init__()
if activation == 'tanh':
self.activation = torch.tanh
... | 10,418 | 38.465909 | 154 | py |
UID | UID-main/code/my_utils/replay_memory.py | from collections import namedtuple
import random
import numpy as np
# Taken from
# https://github.com/pytorch/tutorials/blob/master/Reinforcement%20(Q-)Learning%20with%20PyTorch.ipynb
Transition = namedtuple('Transition', ('state', 'action', 'mask', 'next_state', 'reward', 'latent_code'))
class Memory(object):
d... | 2,220 | 35.409836 | 155 | py |
UID | UID-main/code/my_utils/torch.py | import torch
import numpy as np
from torch.autograd import Variable
use_gpu = torch.cuda.is_available()
device = torch.device("cuda:0" if use_gpu else "cpu")
device_cpu = torch.device("cpu")
DoubleTensor = torch.DoubleTensor
FloatTensor = torch.FloatTensor
LongTensor = torch.LongTensor
ByteTensor = torch.ByteTensor
... | 2,159 | 25.666667 | 102 | py |
UID | UID-main/code/my_utils/math.py | import torch
import math
def normal_entropy(std):
var = std.pow(2)
entropy = 0.5 + 0.5 * torch.log(2 * var * math.pi)
return entropy.sum(1, keepdim=True)
def normal_log_density(x, mean, log_std, std):
var = std.pow(2)
log_density = -(x - mean).pow(2) / (2 * var) - 0.5 * math.log(2 * math.pi) - l... | 371 | 23.8 | 88 | py |
UID | UID-main/code/my_utils/__init__.py | import argparse
import pathlib
import os
import sys
import gym
import time
import platform
import random
import pickle
import torch
import torch.nn.functional as F
import torch.utils.data as data_utils
from torch import nn
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))
from my_util... | 434 | 18.772727 | 79 | py |
tag-based-music-retrieval | tag-based-music-retrieval-master/train/main.py | import os
import torch
import argparse
from solver import Solver
from pytorch_lightning import Trainer
from pytorch_lightning.callbacks import ModelCheckpoint
from pytorch_lightning.loggers.neptune import NeptuneLogger
def main(config):
solver = Solver(config)
logger = NeptuneLogger(project_name=config.neptune_proje... | 2,546 | 38.796875 | 96 | py |
tag-based-music-retrieval | tag-based-music-retrieval-master/train/modules.py | import numpy as np
import torch
import torch.nn as nn
class Conv_2d(nn.Module):
def __init__(self, input_channels, output_channels, shape=3, pooling=2):
super(Conv_2d, self).__init__()
self.conv = nn.Conv2d(input_channels, output_channels, shape, padding=shape//2)
self.bn = nn.BatchNorm2d(output_channels)
se... | 786 | 25.233333 | 81 | py |
tag-based-music-retrieval | tag-based-music-retrieval-master/train/data_loader.py | import os
import sys
import pickle
import tqdm
import numpy as np
import pandas as pd
import random
from torch.utils import data
class MyDataset(data.Dataset):
def __init__(self, data_path, split='TRAIN', input_type='spec', input_length=None, num_chunk=16, w2v_type='google', is_balanced=True, is_subset=False):
sel... | 4,525 | 30.65035 | 152 | py |
tag-based-music-retrieval | tag-based-music-retrieval-master/train/model.py | import torch
from torch import nn
from modules import Conv_2d, Conv_emb
class AudioModel(nn.Module):
def __init__(self):
super(AudioModel, self).__init__()
# CNN module for spectrograms
self.spec_bn = nn.BatchNorm2d(1)
self.layer1 = Conv_2d(1, 128, pooling=2)
self.layer2 = Conv_2d(128, 128, pooling=2)
s... | 4,767 | 23.451282 | 51 | py |
tag-based-music-retrieval | tag-based-music-retrieval-master/train/eval.py | import os
import numpy as np
import torch
from torch import nn
import time
import datetime
import pickle
import tqdm
import pandas as pd
from sklearn import metrics
from sklearn.neighbors import NearestNeighbors
from model import AudioModel, CFModel, HybridModel
class Solver(object):
def __init__(self, data_path, mo... | 3,999 | 28.19708 | 99 | py |
tag-based-music-retrieval | tag-based-music-retrieval-master/train/solver.py | import os
import random
import torch
import time
import pickle
import tqdm
import numpy as np
from sklearn import metrics
from torch import nn
from torch.nn import functional as F
from torch.utils.data import DataLoader
from pytorch_lightning.core.lightning import LightningModule
from data_loader import MyDataset
from... | 9,139 | 34.019157 | 114 | py |
solt | solt-master/setup.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""The setup script."""
from setuptools import find_packages, setup
requirements = ("numpy", "scipy", "opencv-python-headless", "torch", "torchvision", "pyyaml")
setup_requirements = ()
test_requirements = ("pytest",)
description = """Data augmentation library for Dee... | 1,630 | 30.980392 | 127 | py |
solt | solt-master/solt/core/_data.py | import numpy as np
import torch
from solt.constants import ALLOWED_INTERPOLATIONS, ALLOWED_PADDINGS, ALLOWED_TYPES
from solt.utils import validate_parameter
class DataContainer(object):
"""
Data container to encapsulate different types of data, such as images, bounding boxes, etc.
The container itself i... | 15,276 | 34.445476 | 120 | py |
solt | solt-master/solt/core/_core.py | import numpy as np
from ._base_transforms import (
BaseTransform,
MatrixTransform,
)
import copy
import random
from solt.utils import Serializable
from ._data import DataContainer
class Stream(Serializable):
"""
Stream class. Executes the list of transformations.
The stream can be called direct... | 11,910 | 31.279133 | 110 | py |
solt | solt-master/solt/core/_base_transforms.py | import copy
import random
from abc import ABCMeta, abstractmethod
import cv2
import numpy as np
from solt.utils import Serializable
from solt.constants import ALLOWED_INTERPOLATIONS, ALLOWED_PADDINGS
from ._data import DataContainer, Keypoints
from solt.utils import (
img_shape_checker,
validate_parameter,
)
... | 20,280 | 30.010703 | 119 | py |
solt | solt-master/tests/test_data_core.py | import itertools
import random
import cv2
import numpy as np
import pytest
import torch
import solt.core as slc
import solt.transforms as slt
import solt.utils as slu
from .fixtures import *
def assert_data_containers_equal(dc, dc_new):
assert dc_new.data_format == dc.data_format
for d1, d2 in zip(dc_new.d... | 26,073 | 31.309789 | 119 | py |
solt | solt-master/tests/test_transforms.py | import copy
import random
from contextlib import ExitStack as does_not_raise
import cv2
import numpy as np
import pytest
import solt.core as slc
import solt.transforms as slt
from solt.constants import ALLOWED_INTERPOLATIONS, ALLOWED_PADDINGS
from .fixtures import *
from .utils import gen_gs_img_black_edge
def te... | 48,730 | 30.892016 | 114 | py |
solt | solt-master/tests/test_base_transforms.py | import solt.transforms as slt
import solt.core as slc
import numpy as np
import pytest
import sys, inspect
import torch
from .fixtures import *
def get_transforms_solt():
trfs = []
for name, obj in inspect.getmembers(sys.modules["solt.transforms"]):
if inspect.isclass(obj):
trfs.append(ob... | 4,951 | 28.831325 | 117 | py |
solt | solt-master/benchmark/augbench/benchmark.py | import os
import pandas as pd
import cv2
import random
import numpy as np
from tqdm import tqdm
from timeit import Timer
from collections import defaultdict
from augbench import utils
from augbench import transforms
os.environ["OMP_NUM_THREADS"] = "1" # noqa E402
os.environ["OPENBLAS_NUM_THREADS"] = "1" # noqa E40... | 3,006 | 35.670732 | 102 | py |
solt | solt-master/benchmark/augbench/constants.py | DEFAULT_BENCHMARKING_LIBRARIES = ["albumentations", "torchvision", "augmentor", "solt"]
| 88 | 43.5 | 87 | py |
solt | solt-master/benchmark/augbench/utils.py | from PIL import Image
import cv2
import argparse
import os
import pkg_resources
import sys
import math
import numpy as np
from augbench.constants import DEFAULT_BENCHMARKING_LIBRARIES
from pytablewriter import MarkdownTableWriter
from pytablewriter.style import Style
def read_img_pillow(path, imsize):
with open(... | 5,162 | 34.854167 | 119 | py |
solt | solt-master/benchmark/augbench/transforms.py | import cv2
import Augmentor as augmentor
import albumentations as albu
from albumentations.pytorch import ToTensor
import solt
import solt.transforms as slt
from torchvision import transforms as tv_transforms
class BenchmarkTest:
def __init__(self, img_size=256):
self.img_size = img_size
self.albu... | 10,298 | 34.760417 | 109 | py |
solt | solt-master/doc/source/conf.py | # -*- coding: utf-8 -*-
#
# Configuration file for the Sphinx documentation builder.
#
# This file does only contain a selection of the most common options. For a
# full list see the documentation:
# http://www.sphinx-doc.org/en/master/config
# -- Path setup ------------------------------------------------------------... | 5,594 | 29.741758 | 113 | py |
Cutout | Cutout-master/train.py | # run train.py --dataset cifar10 --model resnet18 --data_augmentation --cutout --length 16
# run train.py --dataset cifar100 --model resnet18 --data_augmentation --cutout --length 8
# run train.py --dataset svhn --model wideresnet --learning_rate 0.01 --epochs 160 --cutout --length 20
import pdb
import argparse
import... | 8,610 | 36.277056 | 103 | py |
Cutout | Cutout-master/util/cutout.py | import torch
import numpy as np
class Cutout(object):
"""Randomly mask out one or more patches from an image.
Args:
n_holes (int): Number of patches to cut out of each image.
length (int): The length (in pixels) of each square patch.
"""
def __init__(self, n_holes, length):
se... | 1,172 | 25.659091 | 82 | py |
Cutout | Cutout-master/model/resnet.py | '''ResNet18/34/50/101/152 in Pytorch.'''
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Variable
def conv3x3(in_planes, out_planes, stride=1):
return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride, padding=1, bias=False)
class BasicBlock(nn.Module):... | 4,026 | 32.840336 | 102 | py |
Cutout | Cutout-master/model/wide_resnet.py | # From https://github.com/xternalz/WideResNet-pytorch
import math
import torch
import torch.nn as nn
import torch.nn.functional as F
class BasicBlock(nn.Module):
def __init__(self, in_planes, out_planes, stride, dropRate=0.0):
super(BasicBlock, self).__init__()
self.bn1 = nn.BatchNorm2d(in_planes... | 3,800 | 41.707865 | 116 | py |
StreamingTransformer | StreamingTransformer-master/setup.py | #!/usr/bin/env python3
from distutils.version import LooseVersion
import os
import pip
from setuptools import find_packages
from setuptools import setup
import sys
if LooseVersion(sys.version) < LooseVersion('3.6'):
raise RuntimeError(
'ESPnet requires Python>=3.6, '
'but your Python is {}'.format... | 3,252 | 31.207921 | 82 | py |
StreamingTransformer | StreamingTransformer-master/tools/check_install.py | #!/usr/bin/env python3
# Copyright 2018 Nagoya University (Tomoki Hayashi)
# Apache 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
import argparse
from distutils.version import LooseVersion
import importlib
import logging
import sys
def main(args):
parser = argparse.ArgumentParser()
parser.add_argument(... | 5,984 | 38.635762 | 97 | py |
StreamingTransformer | StreamingTransformer-master/espnet/nets/e2e_asr_common.py | #!/usr/bin/env python3
# Copyright 2017 Johns Hopkins University (Shinji Watanabe)
# Apache 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
"""Common functions for ASR."""
import argparse
import editdistance
import json
import logging
import numpy as np
import six
import sys
from itertools import groupby
def e... | 13,003 | 32.776623 | 85 | py |
StreamingTransformer | StreamingTransformer-master/espnet/nets/ctc_prefix_score.py | #!/usr/bin/env python3
# Copyright 2018 Mitsubishi Electric Research Labs (Takaaki Hori)
# Apache 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
import torch
import numpy as np
import six
class CTCPrefixScoreTH(object):
"""Batch processing of CTCPrefixScore
which is based on Algorithm 2 in WATANABE et... | 13,177 | 38.45509 | 88 | py |
StreamingTransformer | StreamingTransformer-master/espnet/nets/lm_interface.py | """Language model interface."""
import argparse
from espnet.nets.scorer_interface import ScorerInterface
from espnet.utils.dynamic_import import dynamic_import
from espnet.utils.fill_missing_args import fill_missing_args
class LMInterface(ScorerInterface):
"""LM Interface for ESPnet model implementation."""
... | 2,590 | 28.781609 | 82 | py |
StreamingTransformer | StreamingTransformer-master/espnet/nets/scorer_interface.py | """Scorer interface module."""
from typing import Any
from typing import List
from typing import Tuple
import torch
class ScorerInterface:
"""Scorer interface for beam search.
The scorer performs scoring of the all tokens in vocabulary.
Examples:
* Search heuristics
* :class:`espne... | 4,140 | 29.226277 | 85 | py |
StreamingTransformer | StreamingTransformer-master/espnet/nets/scorers/ctc.py | """ScorerInterface implementation for CTC."""
import numpy as np
import torch
from espnet.nets.ctc_prefix_score import CTCPrefixScore
from espnet.nets.scorer_interface import PartialScorerInterface
class CTCPrefixScorer(PartialScorerInterface):
"""Decoder interface wrapper for CTCPrefixScore."""
def __init... | 2,246 | 28.96 | 85 | py |
StreamingTransformer | StreamingTransformer-master/espnet/nets/pytorch_backend/ctc.py | from distutils.version import LooseVersion
import logging
import numpy as np
import torch
import torch.nn.functional as F
from espnet.nets.pytorch_backend.nets_utils import to_device
class CTC(torch.nn.Module):
"""CTC module
:param int odim: dimension of outputs
:param int eprojs: number of encoder pro... | 6,543 | 34.759563 | 87 | py |
StreamingTransformer | StreamingTransformer-master/espnet/nets/pytorch_backend/streaming_transformer.py | # Apache 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
"""Transformer speech recognition model (pytorch)."""
from argparse import Namespace
from collections import defaultdict, Counter
from distutils.util import strtobool
import time
import logging
import math
import numpy as np
import torch
from espnet.nets.... | 39,254 | 44.966042 | 129 | py |
StreamingTransformer | StreamingTransformer-master/espnet/nets/pytorch_backend/nets_utils.py | # -*- coding: utf-8 -*-
"""Network related utility tools."""
import logging
from typing import Dict
import numpy as np
import torch
def to_device(m, x):
"""Send tensor into the device of the module.
Args:
m (torch.nn.Module): Torch module.
x (Tensor): Torch tensor.
Returns:
Te... | 15,368 | 32.703947 | 107 | py |
StreamingTransformer | StreamingTransformer-master/espnet/nets/pytorch_backend/e2e_asr_transformer.py | # Copyright 2019 Shigeki Karita
# Apache 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
"""Transformer speech recognition model (pytorch)."""
from argparse import Namespace
from distutils.util import strtobool
import pdb
import time
import logging
import math
import numpy as np
import torch
from espnet.nets.vi... | 17,909 | 41.240566 | 115 | py |
StreamingTransformer | StreamingTransformer-master/espnet/nets/pytorch_backend/conformer_aed.py | """Transducer speech recognition model (pytorch)."""
from distutils.util import strtobool
import logging
import math
import numpy as np
import torch
import time
import pdb
from espnet.nets.asr_interface import ASRInterface
from espnet.nets.pytorch_backend.nets_utils import make_pad_mask
from espnet.nets.pytorch_... | 13,526 | 39.02071 | 115 | py |
StreamingTransformer | StreamingTransformer-master/espnet/nets/pytorch_backend/lm/default.py | """Default Recurrent Neural Network Languge Model in `lm_train.py`."""
from typing import Any
from typing import List
from typing import Tuple
import torch
import torch.nn as nn
import torch.nn.functional as F
from espnet.nets.lm_interface import LMInterface
from espnet.nets.pytorch_backend.nets_utils import to_devi... | 13,017 | 33.439153 | 88 | py |
StreamingTransformer | StreamingTransformer-master/espnet/nets/pytorch_backend/conformer/encoder.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Copyright 2019 Shigeki Karita
# Apache 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
"""Multi-Head Attention layer definition."""
import math
import logging
import numpy
import torch
from torch import nn
from espnet.nets.pytorch_backend.transformer.embedding im... | 12,505 | 36.89697 | 123 | py |
StreamingTransformer | StreamingTransformer-master/espnet/nets/pytorch_backend/transformer/embedding.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Copyright 2019 Shigeki Karita
# Apache 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
"""Positonal Encoding Module."""
import math
import torch
def _pre_hook(state_dict, prefix, local_metadata, strict,
missing_keys, unexpected_keys, error_msgs):
... | 2,470 | 30.679487 | 88 | py |
StreamingTransformer | StreamingTransformer-master/espnet/nets/pytorch_backend/transformer/encoder_layer.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Copyright 2019 Shigeki Karita
# Apache 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
"""Encoder self-attention layer definition."""
import torch
from torch import nn
from espnet.nets.pytorch_backend.transformer.layer_norm import LayerNorm
class EncoderLayer(n... | 3,097 | 31.610526 | 82 | py |
StreamingTransformer | StreamingTransformer-master/espnet/nets/pytorch_backend/transformer/label_smoothing_loss.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Copyright 2019 Shigeki Karita
# Apache 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
"""Label smoothing module."""
import torch
from torch import nn
class LabelSmoothingLoss(nn.Module):
"""Label-smoothing loss.
:param int size: the number of class
... | 2,164 | 32.828125 | 75 | py |
StreamingTransformer | StreamingTransformer-master/espnet/nets/pytorch_backend/transformer/positionwise_feed_forward.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Copyright 2019 Shigeki Karita
# Apache 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
"""Positionwise feed forward layer definition."""
import torch
class PositionwiseFeedForward(torch.nn.Module):
"""Positionwise feed forward layer.
:param int idim: inp... | 899 | 28.032258 | 62 | py |
StreamingTransformer | StreamingTransformer-master/espnet/nets/pytorch_backend/transformer/subsampling.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Copyright 2019 Shigeki Karita
# Apache 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
"""Subsampling layer definition."""
import math
import torch
import torch.nn.functional as F
from espnet.nets.pytorch_backend.transformer.embedding import PositionalEncoding
c... | 8,661 | 34.211382 | 88 | py |
StreamingTransformer | StreamingTransformer-master/espnet/nets/pytorch_backend/transformer/encoder.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Copyright 2019 Shigeki Karita
# Apache 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
"""Encoder definition."""
import torch
from espnet.nets.pytorch_backend.transformer.attention import MultiHeadedAttention
from espnet.nets.pytorch_backend.transformer.embedding ... | 6,259 | 38.872611 | 96 | py |
StreamingTransformer | StreamingTransformer-master/espnet/nets/pytorch_backend/transformer/multi_layer_conv.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Copyright 2019 Tomoki Hayashi
# Apache 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
"""Layer modules for FFT block in FastSpeech (Feed-forward Transformer)."""
import torch
class MultiLayeredConv1d(torch.nn.Module):
"""Multi-layered conv1d for Transformer ... | 3,148 | 28.707547 | 80 | py |
StreamingTransformer | StreamingTransformer-master/espnet/nets/pytorch_backend/transformer/repeat.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Copyright 2019 Shigeki Karita
# Apache 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
"""Repeat the same layer definition."""
import torch
class MultiSequential(torch.nn.Sequential):
"""Multi-input multi-output torch.nn.Sequential."""
def forward(self, ... | 675 | 20.806452 | 59 | py |
StreamingTransformer | StreamingTransformer-master/espnet/nets/pytorch_backend/transformer/decoder.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Copyright 2019 Shigeki Karita
# Apache 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
"""Decoder definition."""
from typing import Any
from typing import List
from typing import Tuple
import torch
from espnet.nets.pytorch_backend.transformer.attention import Mul... | 9,513 | 40.186147 | 87 | py |
StreamingTransformer | StreamingTransformer-master/espnet/nets/pytorch_backend/transformer/layer_norm.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Copyright 2019 Shigeki Karita
# Apache 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
"""Layer normalization module."""
import torch
class LayerNorm(torch.nn.LayerNorm):
"""Layer normalization module.
:param int nout: output dim size
:param int dim:... | 874 | 24.735294 | 82 | py |
StreamingTransformer | StreamingTransformer-master/espnet/nets/pytorch_backend/transformer/add_sos_eos.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Copyright 2019 Shigeki Karita
# Apache 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
"""Unility funcitons for Transformer."""
import torch
def add_sos_eos(ys_pad, sos, eos, ignore_id):
"""Add <sos> and <eos> labels.
:param torch.Tensor ys_pad: batch of... | 958 | 28.96875 | 74 | py |
StreamingTransformer | StreamingTransformer-master/espnet/nets/pytorch_backend/transformer/attention.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Copyright 2019 Shigeki Karita
# Apache 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
"""Multi-Head Attention layer definition."""
import math
import logging
import numpy
import torch
from torch import nn
class MultiHeadedAttention(nn.Module):
"""Multi-Head... | 2,972 | 36.1625 | 88 | py |
StreamingTransformer | StreamingTransformer-master/espnet/nets/pytorch_backend/transformer/decoder_layer.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Copyright 2019 Shigeki Karita
# Apache 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
"""Decoder self-attention layer definition."""
import torch
from torch import nn
from espnet.nets.pytorch_backend.transformer.layer_norm import LayerNorm
class DecoderLayer(nn... | 4,480 | 34.283465 | 86 | py |
StreamingTransformer | StreamingTransformer-master/espnet/nets/pytorch_backend/transformer/mask.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._... | 1,660 | 30.942308 | 87 | py |
StreamingTransformer | StreamingTransformer-master/espnet/nets/pytorch_backend/transformer/initializer.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Copyright 2019 Shigeki Karita
# Apache 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
"""Parameter initialization."""
import torch
from espnet.nets.pytorch_backend.transformer.layer_norm import LayerNorm
def initialize(model, init_type="pytorch"):
"""Initia... | 1,383 | 29.755556 | 75 | py |
StreamingTransformer | StreamingTransformer-master/espnet/nets/pytorch_backend/transformer/optimizer.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Copyright 2019 Shigeki Karita
# Apache 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
"""Optimizer module."""
import torch
class NoamOpt(object):
"""Optim wrapper that implements rate."""
def __init__(self, model_size, factor, warmup, optimizer):
... | 2,093 | 26.552632 | 82 | py |
StreamingTransformer | StreamingTransformer-master/espnet/bin/asr_recog.py | #!/usr/bin/env python3
# encoding: utf-8
# Copyright 2017 Johns Hopkins University (Shinji Watanabe)
# Apache 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
"""End-to-end speech recognition model decoding script."""
import configargparse
import logging
import os
import random
import sys
import numpy as np
from... | 6,247 | 33.519337 | 122 | py |
StreamingTransformer | StreamingTransformer-master/espnet/bin/asr_train.py | #!/usr/bin/env python3
# encoding: utf-8
"""Automatic speech recognition model training script."""
import logging
import os
import random
import subprocess
import sys
from distutils.version import LooseVersion
import configargparse
import numpy as np
import torch
from espnet.utils.cli_utils import strtobool
from e... | 14,667 | 30.142251 | 88 | py |
StreamingTransformer | StreamingTransformer-master/espnet/asr/asr_utils.py | #!/usr/bin/env python3
# Copyright 2017 Johns Hopkins University (Shinji Watanabe)
# Apache 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
import argparse
import copy
import json
import logging
# matplotlib related
import os
import shutil
import tempfile
# chainer related
import chainer
from chainer.training im... | 8,978 | 28.152597 | 88 | py |
StreamingTransformer | StreamingTransformer-master/espnet/asr/pytorch_backend/asr_recog.py | #!/usr/bin/env python3
# encoding: utf-8
# Copyright 2017 Johns Hopkins University (Shinji Watanabe)
# Apache 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
"""Training/decoding definition for the speech recognition task."""
import json
import logging
import os
import numpy as np
import torch
from espnet.asr.a... | 6,248 | 34.106742 | 110 | py |
StreamingTransformer | StreamingTransformer-master/espnet/asr/pytorch_backend/asr_init.py | """Finetuning methods."""
import logging
import os
import torch
from collections import OrderedDict
from espnet.asr.asr_utils import get_model_conf
from espnet.asr.asr_utils import torch_load
from espnet.utils.dynamic_import import dynamic_import
def transfer_verification(model_state_dict, partial_state_dict, mod... | 7,997 | 30.242188 | 83 | py |
StreamingTransformer | StreamingTransformer-master/espnet/asr/pytorch_backend/asr_ddp.py | #!/usr/bin/env python3
# encoding: utf-8
# Copyright 2017 Johns Hopkins University (Shinji Watanabe)
# Apache 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
"""Training/decoding definition for the speech recognition task."""
import json
import math
import os
import time
import logging
import numpy as np
import ... | 16,241 | 39.20297 | 137 | py |
StreamingTransformer | StreamingTransformer-master/espnet/utils/spec_augment.py | # -*- coding: utf-8 -*-
"""
This implementation is modified from https://github.com/zcaceres/spec_augment
MIT License
Copyright (c) 2019 Zach Caceres
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 Soft... | 18,470 | 36.16499 | 88 | py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.