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 |
|---|---|---|---|---|---|---|
omni | omni-master/torch-ac/torch_ac/algos/a2c.py | import numpy
import torch
import torch.nn.functional as F
from torch_ac.algos.base import BaseAlgo
class A2CAlgo(BaseAlgo):
"""The Advantage Actor-Critic algorithm."""
def __init__(self, envs, acmodel, device=None, num_frames_per_proc=None, discount=0.99, lr=0.01, gae_lambda=0.95,
entropy_co... | 3,659 | 31.972973 | 117 | py |
omni | omni-master/torch-ac/torch_ac/algos/ppo.py | import numpy
import torch
import torch.nn.functional as F
from torch_ac.algos.base import BaseAlgo
class PPOAlgo(BaseAlgo):
"""The Proximal Policy Optimization algorithm
([Schulman et al., 2015](https://arxiv.org/abs/1707.06347))."""
def __init__(self, envs, acmodel, device=None, num_frames_per_proc=None... | 6,011 | 37.292994 | 118 | py |
omni | omni-master/torch-ac/torch_ac/algos/__init__.py | from torch_ac.algos.a2c import A2CAlgo
from torch_ac.algos.ppo import PPOAlgo | 77 | 38 | 38 | py |
omni | omni-master/torch-ac/torch_ac/utils/__init__.py | from torch_ac.utils.dictlist import DictList
from torch_ac.utils.penv import ParallelEnv | 88 | 43.5 | 44 | py |
omni | omni-master/utils/prep_train.py | import os
import argparse
import json
import numpy as np
from envs import env_alltasks
from envs.env_utils import ach_to_string
from utils.other import root_path
from torch_ac.utils import ParallelEnv
def get_rdn_tsr(env):
with open(os.path.join(root_path, './utils/prep_train.json'), 'r') as f:
data = js... | 3,516 | 36.021053 | 120 | py |
omni | omni-master/utils/storage.py | import csv
import os
import torch
import logging
import sys
import utils
from .other import device
def create_folders_if_necessary(path):
dirname = os.path.dirname(path)
if not os.path.isdir(dirname):
os.makedirs(dirname)
def get_storage_dir():
if "RL_STORAGE" in os.environ:
return os.e... | 1,582 | 22.279412 | 56 | py |
omni | omni-master/utils/format.py | import os
import json
import numpy as np
import re
import torch
import torch_ac
import utils
def get_obss_preprocessor(obs_space):
prep_obs_space = {}
for key in obs_space.keys():
prep_obs_space[key] = obs_space[key].shape
def preprocess_obss(obss, device=None):
prep_obss = dict()
... | 1,028 | 26.810811 | 97 | py |
omni | omni-master/utils/agent.py | import torch
import utils
from .other import device
from model import ACModel
class Agent:
"""An agent.
It is able:
- to choose an action given an observation,
- to analyze the feedback (i.e. reward and done state) of its action."""
def __init__(self, preprocess_obss, acmodel, argmax, num_envs)... | 2,234 | 32.358209 | 95 | py |
omni | omni-master/utils/other.py | import random
import numpy
import torch
import collections
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
root_path = './'
def seed(seed):
random.seed(seed)
numpy.random.seed(seed)
torch.manual_seed(seed)
if torch.cuda.is_available():
torch.cuda.manual_seed_all(seed)
... | 523 | 19.153846 | 69 | py |
CE-Net | CE-Net-master/src/main.py | # *coding:utf-8 *
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from _init_paths import __init_path
__init_path()
import os
import torch
import torch.utils
from logger import Logger
from datasets.dataset_factory import get_dataset
from models.model imp... | 4,194 | 32.031496 | 96 | py |
CE-Net | CE-Net-master/src/lib/logger.py | # *coding:utf-8 *
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
import time
import sys
import torch
USE_TENSORBOARD = True
try:
import tensorboardX
print("Using tensorboardX")
except:
USE_TENSORBOARD = False
class Logger(object):
... | 2,409 | 29.897436 | 79 | py |
CE-Net | CE-Net-master/src/lib/models/losses.py | # *coding:utf-8 *
import torch
import torch.nn as nn
from torch.autograd import Variable as V
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Variable
from utils.image import mask_to_boundary
import cv2
import numpy as np
class weighted_cross_entropy(nn.Module):
de... | 7,925 | 31.617284 | 101 | py |
CE-Net | CE-Net-master/src/lib/models/data_parallel.py | import torch
from torch.nn.modules import Module
from torch.nn.parallel.scatter_gather import gather
from torch.nn.parallel.replicate import replicate
from torch.nn.parallel.parallel_apply import parallel_apply
from .scatter_gather import scatter_kwargs
class _DataParallel(Module):
r"""Implements data parallelis... | 5,105 | 39.204724 | 101 | py |
CE-Net | CE-Net-master/src/lib/models/model.py | # *coding:utf-8 *
import torch
from .networks.cenet import CE_Net_
_model_factory = {
'cenet': CE_Net_
}
def create_model(model_name):
get_model = _model_factory[model_name]
model = get_model()
return model
def load_model(model, model_path, optimizer=None, resume=False,
lr=None, lr... | 2,898 | 33.511905 | 82 | py |
CE-Net | CE-Net-master/src/lib/models/scatter_gather.py | import torch
from torch.autograd import Variable
from torch.nn.parallel._functions import Scatter, Gather
def scatter(inputs, target_gpus, dim=0, chunk_sizes=None):
r"""
Slices variables into approximately equal chunks and
distributes them across given GPUs. Duplicates
references to objects that are n... | 1,535 | 38.384615 | 77 | py |
CE-Net | CE-Net-master/src/lib/models/networks/cenet.py | # *coding:utf-8 *
import torch
import torch.nn as nn
from torchvision import models
import torch.nn.functional as F
from .backbones.resnet.resnet_factory import get_resnet_backbone
from functools import partial
nonlinearity = partial(F.relu, inplace=True)
class DACblock(nn.Module):
def __init__(self, channel)... | 19,284 | 33.132743 | 119 | py |
CE-Net | CE-Net-master/src/lib/models/networks/neck_blocks/attention_modules/Dense_atrous.py | import torch
import torch.nn as nn
import torch.nn.functional as F
from functools import partial
nonlinearity = partial(nn.ReLU, inplace=True)
class DACblock(nn.Module):
def __init__(self, channel):
super(DACblock, self).__init__()
self.dilate1 = nn.Conv2d(channel, channel, kernel_size=3, dilati... | 2,655 | 39.861538 | 116 | py |
CE-Net | CE-Net-master/src/lib/models/networks/backbones/mobilenet/build_mobilenet.py | import torch
from torch import nn
import torch.utils.model_zoo as model_zoo
from .basic_module import ConvBNReLU, InvertedResidual, _make_divisible, load_model
model_urls = {
'mobilenetv2_10': 'https://download.pytorch.org/models/mobilenet_v2-b0353104.pth',
}
class MobileNetV2(nn.Module):
def __init__(self,... | 3,414 | 28.95614 | 93 | py |
CE-Net | CE-Net-master/src/lib/models/networks/backbones/mobilenet/basic_module.py | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from torch import nn
from collections import OrderedDict
def _make_divisible(v, divisor, min_value=None):
"""
This function is taken from the original pytorch repo
It ensures that all layers have ... | 2,546 | 22.583333 | 82 | py |
CE-Net | CE-Net-master/src/lib/models/networks/backbones/resnet/basic_module.py | # ------------------------------------------------------------------------------
# Copyright (c) Microsoft
# Licensed under the MIT License.
# Written by Bin Xiao (Bin.Xiao@microsoft.com)
# Modified by Dequan Wang and Xingyi Zhou
# ------------------------------------------------------------------------------
from __f... | 2,602 | 27.922222 | 90 | py |
CE-Net | CE-Net-master/src/lib/models/networks/backbones/resnet/build_resnet.py | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from .basic_module import BasicBlock, Bottleneck, BN_MOMENTUM
import torch.nn as nn
import torch.utils.model_zoo as model_zoo
model_urls = {
'resnet18': 'https://download.pytorch.org/models/resnet18-5c106... | 3,953 | 30.887097 | 85 | py |
CE-Net | CE-Net-master/src/lib/trains/base_trainer.py | # *coding:utf-8 *
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import time
import torch
from progress.bar import Bar
from models.data_parallel import DataParallel
from utils.utils import AverageMeter
class ModelWithLoss(torch.nn.Module):
def __init... | 4,490 | 33.022727 | 98 | py |
CE-Net | CE-Net-master/src/lib/trains/binarySeg.py | # *coding:utf-8 *
import torch
import numpy as np
from models.losses import dice_bce_loss
from .base_trainer import BaseTrainer
class binarySegLoss(torch.nn.Module):
def __init__(self, opt):
super(binarySegLoss, self).__init__()
self.crit = dice_bce_loss()
self.opt = opt
def forward(... | 762 | 22.121212 | 79 | py |
CE-Net | CE-Net-master/src/lib/datasets/sample/multiSeg.py | # *coding:utf-8 *
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import torch
import torch.utils.data as data
from torch.autograd import Variable as V
import cv2
import numpy as np
from PIL import Image
from utils.image import randomHueSaturationValue
fr... | 1,901 | 32.964286 | 78 | py |
CE-Net | CE-Net-master/src/lib/datasets/sample/binarySeg.py | # *coding:utf-8 *
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import torch
import torch.utils.data as data
from torch.autograd import Variable as V
import cv2
import numpy as np
from PIL import Image
from utils.image import randomHueSaturationValue
fr... | 2,117 | 32.09375 | 78 | py |
CE-Net | CE-Net-master/src/lib/datasets/dataset/HumanSeg.py | # *coding:utf-8 *
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
import os
import torch.utils.data as data
class HumanSeg(data.Dataset):
num_classes = 1
default_resolution = [448, 448]
mean = np.array([0.40789654, 0.44719... | 1,562 | 33.733333 | 99 | py |
CE-Net | CE-Net-master/src/lib/datasets/dataset/ORIGA_OD.py | # *coding:utf-8 *
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
import os
import torch.utils.data as data
class ORIGA_OD(data.Dataset):
num_classes = 1
default_resolution = [448, 448]
mean = np.array([0.40789654, 0.44719... | 1,541 | 32.521739 | 99 | py |
CE-Net | CE-Net-master/src/lib/datasets/dataset/Cityscape.py | # *coding:utf-8 *
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
import os
import torch.utils.data as data
class Cityscape(data.Dataset):
num_classes = 1
default_resolution = [448, 448]
mean = np.array([0.40789654, 0.447193... | 1,541 | 33.266667 | 99 | py |
CE-Net | CE-Net-master/src/lib/datasets/dataset/VOC.py | # *coding:utf-8 *
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
import os
import torch.utils.data as data
class VOC(data.Dataset):
num_classes = 1
default_resolution = [448, 448]
mean = np.array([0.40789654, 0.44719302, 0... | 1,537 | 31.723404 | 99 | py |
CE-Net | CE-Net-master/src/lib/utils/image.py | # *coding:utf-8 *
"""
Based on https://github.com/asanakoy/kaggle_carvana_segmentation
"""
import torch
import torch.utils.data as data
from torch.autograd import Variable as V
from PIL import Image
import cv2
import numpy as np
import os
import scipy.misc as misc
def randomHueSaturationValue(image, hue_shift_lim... | 4,360 | 34.745902 | 111 | py |
pp_image_registration | pp_image_registration-main/src/joint_computations/spdz.py | from time import time
from typing import List
import hydra
import numpy as np
import syft as sy
import torch
from src.joint_computations.abstract_jc import AbstractJC
PARTY_1 = 0
PARTY_2 = 1
class SPDZ(AbstractJC):
def __init__(self, n_parties: int, *args, **kwargs):
super().__init__(*args, **kwargs)
... | 2,971 | 36.15 | 123 | py |
pysindy | pysindy-master/docs/conf.py | import importlib
import shutil
from pathlib import Path
author = "dynamicslab"
project = "pysindy" # package name
# no need to edit below this line
copyright = f"2020, {author}"
module = importlib.import_module(project)
version = release = getattr(module, "__version__")
master_doc = "index"
extensions = [
"... | 3,905 | 27.304348 | 80 | py |
NICE-GAN-pytorch | NICE-GAN-pytorch-master/main.py | from NICE import NICE
import argparse
from utils import *
"""parsing and configuration"""
def parse_args():
desc = "Pytorch implementation of NICE-GAN"
parser = argparse.ArgumentParser(description=desc)
parser.add_argument('--phase', type=str, default='train', help='[train / test]')
parser.add_argumen... | 3,570 | 40.523256 | 121 | py |
NICE-GAN-pytorch | NICE-GAN-pytorch-master/NICE.py | import time, itertools
from dataset import ImageFolder
from torchvision import transforms
from torch.utils.data import DataLoader
from networks import *
from utils import *
from glob import glob
# import torch.utils.tensorboard as tensorboardX
from thop import profile
from thop import clever_format
class NICE(object) ... | 22,664 | 48.058442 | 198 | py |
NICE-GAN-pytorch | NICE-GAN-pytorch-master/utils.py | from scipy import misc
import os, cv2, torch
import numpy as np
def load_test_data(image_path, size=256):
img = misc.imread(image_path, mode='RGB')
img = misc.imresize(img, [size, size])
img = np.expand_dims(img, axis=0)
img = preprocessing(img)
return img
def preprocessing(x):
x = x/127.5 - ... | 1,748 | 25.5 | 86 | py |
NICE-GAN-pytorch | NICE-GAN-pytorch-master/dataset.py | import torch.utils.data as data
from PIL import Image
import os
import os.path
def has_file_allowed_extension(filename, extensions):
"""Checks if a file is an allowed extension.
Args:
filename (string): path to a file
Returns:
bool: True if the filename ends with a known image extensio... | 3,477 | 30.908257 | 110 | py |
NICE-GAN-pytorch | NICE-GAN-pytorch-master/networks.py | import torch
import torch.nn as nn
from torch.nn.parameter import Parameter
class ResnetGenerator(nn.Module):
def __init__(self, input_nc, output_nc, ngf=64, n_blocks=6, img_size=256, light=False):
assert(n_blocks >= 0)
super(ResnetGenerator, self).__init__()
self.input_nc = input_nc
... | 16,133 | 40.797927 | 134 | py |
NICE-GAN-pytorch | NICE-GAN-pytorch-master/metric/fid_kid.py | #!/usr/bin/env python3
"""Calculates the Frechet Inception Distance (FID) and The Kernel Inception Distance (KID) to evalulate GANs
The FID and KID is calculated by assuming that X_1 and X_2 are the activations of
the pool_3 layer of the inception net for generated samples and real world
samples respectively.
Code ap... | 15,512 | 34.417808 | 108 | py |
NICE-GAN-pytorch | NICE-GAN-pytorch-master/metric/inception.py | import torch
import torch.nn as nn
import torch.nn.functional as F
from torchvision import models
try:
from torchvision.models.utils import load_state_dict_from_url
except ImportError:
from torch.utils.model_zoo import load_url as load_state_dict_from_url
# Inception weights ported to Pytorch from
# http://do... | 11,623 | 36.376206 | 126 | py |
timmdocs | timmdocs-master/timmdocs/_nbdev.py | # AUTOGENERATED BY NBDEV! DO NOT EDIT!
__all__ = ["index", "modules", "custom_doc_links", "git_url"]
index = {}
modules = []
doc_url = "https://timm.fast.ai/"
git_url = "https://github.com/fastai/timmdocs/tree/master/"
def custom_doc_links(name): return None
| 265 | 18 | 61 | py |
MetaTTE | MetaTTE-main/main.py | # -*- coding: utf-8 -*-
# @Author : morningstarwang
# @FileName: main.py
# @Blog: wangchenxing.com
import configparser
import argparse
import datetime
import os
import sys
import random
import numpy as np
import models
import tensorflow as tf
from tensorflow.python.keras import backend as K
import my_config
from da... | 13,572 | 45.642612 | 129 | py |
MetaTTE | MetaTTE-main/models/base_model.py | # -*- coding: utf-8 -*-
# @Author : morningstarwang
# @FileName: base_model.py
# @Blog: wangchenxing.com
import tensorflow as tf
import my_config
class BaseModel(tf.keras.Model):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.lstm = tf.keras.layers.LSTM(128)
... | 2,260 | 31.3 | 90 | py |
MetaTTE | MetaTTE-main/models/base_model_with_embedding.py | # -*- coding: utf-8 -*-
# @Author : morningstarwang
# @FileName: base_model.py
# @Blog: wangchenxing.com
import tensorflow as tf
import my_config
class BaseModelWithEmbedding(tf.keras.Model):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.time_embedding = tf.keras.l... | 5,248 | 48.056075 | 116 | py |
MetaTTE | MetaTTE-main/models/mstte_model.py | # -*- coding: utf-8 -*-
# @Time : 2020/9/24 11:22 下午
# @Author : morningstarwang
# @FileName: mstte_model.py
# @Blog: wangchenxing.com
import tensorflow as tf
import my_config
# 3 GRU + Att
class MSMTTEGRUAttModel(tf.keras.Model):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs... | 28,036 | 54.082515 | 116 | py |
carsus | carsus-master/docs/conf.py | # -*- coding: utf-8 -*-
# Licensed under a 3-clause BSD style license - see LICENSE.rst
#
# Astropy documentation build configuration file.
#
# 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 file.
#
# All configurati... | 8,518 | 34.495833 | 89 | py |
blue_zero | blue_zero-main/setup.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
import setuptools
import numpy as np
from distutils.core import setup, Extension
from Cython.Distutils import build_ext
pkg_name = 'blue_zero'
author = "Sean P. Cornelius"
author_email = "spcornelius@gmail.com"
install_requires = ['argparse', 'contextlib2', 'w... | 1,310 | 29.488372 | 65 | py |
blue_zero | blue_zero-main/scripts/train.py | from dataclasses import dataclass, asdict
from pathlib import Path
import numpy as np
import torch
from simple_parsing import ArgumentParser, field
import blue_zero.util as util
from blue_zero.mode import BlueMode
from blue_zero.params import HyperParams
from blue_zero.qnet.base import QNet
from blue_zero.replay impo... | 2,731 | 28.06383 | 78 | py |
blue_zero | blue_zero-main/blue_zero/gui.py | from typing import Tuple, Union
import numpy as np
import contextlib
with contextlib.redirect_stdout(None):
import pygame
from pygame_widgets.button import ButtonArray
from torch import Tensor
import blue_zero.config as cfg
__all__ = ["BlueGUI"]
font_size = [100, 100]
class BlueGUI(object):
def __init__... | 3,252 | 32.885417 | 75 | py |
blue_zero | blue_zero-main/blue_zero/replay.py | import random
from collections import namedtuple
from typing import Tuple
import torch
import numpy as np
from blue_zero.mode.base import BlueMode
__all__ = []
__all__.extend([
'Transition',
'NStepReplayMemory',
])
Transition = namedtuple('Transition',
('s_prev', 'a', 's', 'dr', 'ter... | 3,754 | 34.093458 | 91 | py |
blue_zero | blue_zero-main/blue_zero/agent.py | import abc
import numpy as np
import sys
import torch
from more_itertools import chunked
from torch.nn.functional import softmax
from tqdm import tqdm
from typing import Union, Iterable
from blue_zero.mode import BlueMode
from blue_zero.qnet import QNet
__all__ = []
__all__.extend([
'Agent', 'QAgent', 'EpsGreedyQ... | 3,767 | 27.984615 | 78 | py |
blue_zero | blue_zero-main/blue_zero/util.py | import blue_zero.config as cfg
import torch
import os
import random
import numpy as np
from wurlitzer import pipes
from torch.nn import Conv2d
__all__ = ['init_weights', 'to_bitboard', 'set_seed']
def init_weights(module):
def _init_weights(m):
if isinstance(m, Conv2d):
torch.nn.init.uniform... | 1,213 | 25.977778 | 70 | py |
blue_zero | blue_zero-main/blue_zero/trainer.py | import numpy as np
import torch
import torch.optim as optim
from copy import deepcopy
from torch.nn.utils import clip_grad_norm_
from tqdm import tqdm
from typing import Iterable
from blue_zero.agent import QAgent, EpsGreedyQAgent, SoftMaxQAgent
from blue_zero.mode import BlueMode
from blue_zero.params import TrainPar... | 9,877 | 33.78169 | 79 | py |
blue_zero | blue_zero-main/blue_zero/qnet/base.py | import abc
from dataclasses import dataclass, is_dataclass, asdict
from pathlib import Path
from typing import Union, List
import numpy as np
import torch
from torch.nn import Module, Parameter
from blue_zero.config import Status
__all__ = ['QNet']
# map human-readable qnet identifiers ('dueling', etc.) to the appr... | 3,282 | 29.398148 | 75 | py |
blue_zero | blue_zero-main/blue_zero/qnet/simple.py | from dataclasses import dataclass
from typing import Union, Tuple
import torch
from torch.nn import Conv2d, ModuleList
from torch.nn.functional import leaky_relu
from blue_zero.qnet.base import QNet
__all__ = ['SimpleQNet']
@dataclass(eq=False)
class SimpleQNet(QNet, id='simple'):
num_feat: int
depth: int
... | 2,900 | 33.535714 | 77 | py |
blue_zero | blue_zero-main/blue_zero/qnet/dilation.py | from typing import Union, Tuple
from dataclasses import dataclass
import torch
from torch.nn import Conv2d, Module, ReLU, Sequential
from blue_zero.qnet.base import QNet
__all__ = ['DilationQNet']
class DilationEmbeddingBlock(Module):
def __init__(self, c: int,
dilation: Union[int, Tuple[int, ... | 2,893 | 32.651163 | 75 | py |
blue_zero | blue_zero-main/blue_zero/qnet/dueling.py | from dataclasses import dataclass
from functools import partial
from typing import Union, Tuple
import torch
from torch.nn import Conv2d, ReLU, Sequential, BatchNorm2d, Identity
from torch.nn.functional import relu
from blue_zero.qnet.base import QNet
__all__ = ['DuelingQNet']
@dataclass(eq=False)
class DuelingQNe... | 4,566 | 38.034188 | 79 | py |
WARP-Q | WARP-Q-main/WARPQ/WARPQmetric.py | import librosa, librosa.core, librosa.display
import pandas as pd
import numpy as np
from pyvad import vad #, trim, split
from skimage.util.shape import view_as_windows
import speechpy
import soundfile as sf
import os
import zipfile
import tempfile
import pickle
import keras
class warpqMetric(object):
'''
warp... | 13,014 | 40.714744 | 182 | py |
eznlp | eznlp-master/setup.py | # -*- coding: utf-8 -*-
import os
import re
from setuptools import setup, find_packages
HERE = os.path.dirname(os.path.realpath(__file__))
with open(os.path.join(HERE, "README.md"), encoding='utf-8') as f:
readme = f.read()
with open(os.path.join(HERE, 'eznlp', '__init__.py'), encoding='utf-8') as f:
version =... | 1,535 | 35.571429 | 77 | py |
eznlp | eznlp-master/eznlp/wrapper.py | # -*- coding: utf-8 -*-
import torch
def _create_is_like(criterion):
def _is_like(x):
if criterion(x):
return True
elif isinstance(x, list):
return all(criterion(xi) or _is_like(xi) for xi in x)
elif isinstance(x, dict):
return all(criterion(xi) or _is_li... | 3,923 | 32.538462 | 146 | py |
eznlp | eznlp-master/eznlp/vectors.py | # -*- coding: utf-8 -*-
from typing import Union, List
import os
import tqdm
import logging
import torch
logger = logging.getLogger(__name__)
def _parse_line(line: bytes):
w, *vector = line.rstrip().split(b" ")
return w, [float(v) for v in vector]
def _infer_shape(path: str, skiprows: List[int]):
vec_d... | 5,206 | 30.75 | 120 | py |
eznlp | eznlp-master/eznlp/dataset.py | # -*- coding: utf-8 -*-
from typing import List, Any
import random
import torch
from .nn.functional import seq_lens2mask
from .wrapper import Batch
from .model.model import ModelConfigBase
from .plm import PreTrainingConfig
class Dataset(torch.utils.data.Dataset):
def __init__(self, data: List[dict], config: Mod... | 6,823 | 37.337079 | 116 | py |
eznlp | eznlp-master/eznlp/vocab.py | # -*- coding: utf-8 -*-
from typing import List
from collections import Counter
class Vocab(object):
"""A vocabulary object.
This class is modified based on `torchtext.vocab.Vocab` of version 0.8.1.
"""
def __init__(self, counter: Counter, max_size=None, min_freq=1, specials=('<unk>', '<pad>'), ... | 1,830 | 30.033898 | 118 | py |
eznlp | eznlp-master/eznlp/config.py | # -*- coding: utf-8 -*-
from typing import List, Mapping
from collections import OrderedDict
import logging
import torch
logger = logging.getLogger(__name__)
def _add_indents(config_str: str, num_spaces: int=2):
lines = config_str.split('\n')
if len(lines) == 1:
return config_str
else:
li... | 5,254 | 30.656627 | 106 | py |
eznlp | eznlp-master/eznlp/__init__.py | # -*- coding: utf-8 -*-
import torch
import flair
flair.device = torch.device('cpu')
__version__ = '0.2.4'
from .training import auto_device
from eznlp import io
from eznlp import nn
from eznlp import model
from eznlp import training
from eznlp import utils
| 261 | 16.466667 | 34 | py |
eznlp | eznlp-master/eznlp/nn/functional.py | # -*- coding: utf-8 -*-
import torch
def seq_lens2mask(seq_lens: torch.LongTensor, max_len: int=None):
"""Convert `seq_lens` to `mask`.
Parameters
----------
seq_lens : torch.LongTensor (batch, )
max_len : int, optional
Returns
-------
mask : torch.BoolTensor (batch, step)
... | 10,135 | 35.460432 | 128 | py |
eznlp | eznlp-master/eznlp/nn/utils.py | # -*- coding: utf-8 -*-
import torch
def pad_seqs(seqs, padding_value=0.0, length=None):
"""Pad a list of list, making it prepared as a tensor.
"""
# Alternative: `torch.nn.utils.rnn.pad_sequence` which pads a list of tensors.
maxlen = max(len(s) for s in seqs)
length = maxlen if length is None e... | 1,662 | 30.980769 | 82 | py |
eznlp | eznlp-master/eznlp/nn/init.py | # -*- coding: utf-8 -*-
from typing import List
import functools
import logging
import torch
import transformers
logger = logging.getLogger(__name__)
def reinit_embedding_(embedding: torch.nn.Embedding):
uniform_range = (3 / embedding.weight.size(1)) ** 0.5
torch.nn.init.uniform_(embedding.weight.data,... | 7,581 | 38.489583 | 106 | py |
eznlp | eznlp-master/eznlp/nn/modules/embedding.py | # -*- coding: utf-8 -*-
import torch
class SinusoidPositionalEncoding(torch.nn.Module):
def __init__(self, num_embeddings: int, embedding_dim: int, base: int=10000, scale: float=None):
super().__init__()
assert embedding_dim % 2 == 0
self.scale = (embedding_dim**-0.5) if scale is None else... | 929 | 37.75 | 122 | py |
eznlp | eznlp-master/eznlp/nn/modules/aggregation.py | # -*- coding: utf-8 -*-
from typing import Union, List
import torch
from ..functional import sequence_pooling, rnn_last_selecting, sequence_group_aggregating
class SequencePooling(torch.nn.Module):
"""Pooling values over steps.
Parameters
----------
x: torch.FloatTensor (batch, step, hid_dim)
... | 3,169 | 34.222222 | 105 | py |
eznlp | eznlp-master/eznlp/nn/modules/query_bert_like.py | # -*- coding: utf-8 -*-
import copy
import math
import torch
import transformers
class QueryBertLikeSelfAttention(torch.nn.Module):
def __init__(self, origin: transformers.models.bert.modeling_bert.BertSelfAttention, share_weights: bool=False):
super().__init__()
self.num_attention_heads = origin.... | 7,262 | 44.39375 | 138 | py |
eznlp | eznlp-master/eznlp/nn/modules/block.py | # -*- coding: utf-8 -*-
import torch
from ..init import reinit_layer_
from ..utils import _nonlinearity2activation
from .attention import MultiheadAttention
class FeedForwardBlock(torch.nn.Module):
def __init__(self, in_dim: int, out_dim: int, drop_rate: float=0.5, nonlinearity: str='relu'):
super().__in... | 8,089 | 44.449438 | 162 | py |
eznlp | eznlp-master/eznlp/nn/modules/loss.py | # -*- coding: utf-8 -*-
import torch
from ..functional import soft_label_cross_entropy, smooth_label_cross_entropy, focal_loss
class SoftLabelCrossEntropyLoss(torch.nn.modules.loss._WeightedLoss):
def __init__(self, weight: torch.Tensor=None, reduction: str='none'):
weight = weight if weight is None or i... | 2,159 | 43.081633 | 157 | py |
eznlp | eznlp-master/eznlp/nn/modules/dropout.py | # -*- coding: utf-8 -*-
import torch
class CombinedDropout(torch.nn.Module):
def __init__(self, p: float=0.0, word_p: float=0.05, locked_p: float=0.5):
super().__init__()
if p > 0:
self.dropout = torch.nn.Dropout(p)
if word_p > 0:
self.word_dropout = WordDropout(wor... | 2,602 | 30.743902 | 91 | py |
eznlp | eznlp-master/eznlp/nn/modules/crf.py | # -*- coding: utf-8 -*-
import torch
class CRF(torch.nn.Module):
"""Linear-chain conditional random field.
Given the source sequence $x = \{x_1, x_2, \dots, x_T \}$ and the target
sequence $y = \{y_1, y_2, \dots, y_T \}$, the linear-chain CRF models the
conditional probability as:
$$
P... | 7,667 | 41.131868 | 132 | py |
eznlp | eznlp-master/eznlp/nn/modules/attention.py | # -*- coding: utf-8 -*-
import torch
from ..init import reinit_layer_, reinit_vector_parameter_
from ..utils import _nonlinearity2activation
# TODO: Scaling factor for other scoring?
class SequenceAttention(torch.nn.Module):
"""Attention over steps.
Notes
-----
* If `external_query` is True, t... | 10,038 | 43.22467 | 181 | py |
eznlp | eznlp-master/eznlp/training/plm_trainer.py | # -*- coding: utf-8 -*-
import torch
from .trainer import Trainer
class MaskedLMTrainer(Trainer):
def __init__(self, model: torch.nn.Module, **kwargs):
super().__init__(model, **kwargs)
def forward_batch(self, batch):
batch_inputs = {'input_ids': batch.mlm_tok_ids,
... | 992 | 33.241379 | 116 | py |
eznlp | eznlp-master/eznlp/training/utils.py | # -*- coding: utf-8 -*-
from typing import Union, List
import logging
import subprocess
import torch
import numpy
import matplotlib
logger = logging.getLogger(__name__)
class LRLambda(object):
@staticmethod
def constant_lr():
return lambda step: 1.0
@staticmethod
def constant_lr_with... | 6,314 | 37.042169 | 119 | py |
eznlp | eznlp-master/eznlp/training/trainer.py | # -*- coding: utf-8 -*-
import time
import numpy
import logging
import torch
from ..wrapper import Batch
from ..dataset import Dataset
from ..model.model import ModelBase
logger = logging.getLogger(__name__)
class Trainer(object):
"""
Parameters
----------
num_grad_acc_steps: int
The "real" ... | 15,634 | 40.804813 | 145 | py |
eznlp | eznlp-master/eznlp/plm/mlm.py | # -*- coding: utf-8 -*-
from typing import List
import random
import torch
import transformers
from ..nn.functional import seq_lens2mask
from .base import PreTrainingConfig
class MaskedLMConfig(PreTrainingConfig):
"""Configurations for masked LM pretraining, optionally with a sentence pair task (e.g., NSP, SOP)... | 9,453 | 46.747475 | 136 | py |
eznlp | eznlp-master/eznlp/model/span_bert_like.py | # -*- coding: utf-8 -*-
from typing import List
from collections import OrderedDict
import torch
import transformers
from ..nn.modules import SequencePooling, SequenceAttention
from ..nn.modules import QueryBertLikeEncoder
from ..config import Config
class SpanBertLikeConfig(Config):
def __init__(self, **kwargs)... | 5,888 | 45.738095 | 155 | py |
eznlp | eznlp-master/eznlp/model/bert_like.py | # -*- coding: utf-8 -*-
from typing import List
import logging
import re
import tqdm
import numpy
import truecase
import torch
import transformers
from ..utils import find_ascending
from ..token import TokenSequence
from ..nn.modules import SequenceGroupAggregating, ScalarMix
from ..nn.functional import seq_lens2mask
... | 30,057 | 43.596439 | 186 | py |
eznlp | eznlp-master/eznlp/model/image_encoder.py | # -*- coding: utf-8 -*-
from typing import List
import torch
import torchvision
from ..config import Config
class ImageEncoderConfig(Config):
def __init__(self, **kwargs):
self.arch = kwargs.pop('arch', 'ResNet')
self.in_channels = kwargs.pop('in_channels', 3)
self.transforms: torch.nn.Mo... | 4,236 | 31.343511 | 116 | py |
eznlp | eznlp-master/eznlp/model/embedder.py | # -*- coding: utf-8 -*-
from typing import List
from collections import Counter
import logging
import torch
from ..token import TokenSequence
from ..nn import SinusoidPositionalEncoding
from ..nn.init import reinit_embedding_, reinit_embedding_by_pretrained_, reinit_layer_
from ..config import Config
from ..vocab impo... | 7,831 | 34.438914 | 140 | py |
eznlp | eznlp-master/eznlp/model/flair.py | # -*- coding: utf-8 -*-
from typing import List
import torch
import flair
from ..token import TokenSequence
from ..nn.modules import SequenceGroupAggregating
from ..config import Config
class FlairConfig(Config):
def __init__(self, **kwargs):
self.flair_lm: flair.models.LanguageModel = kwargs.pop('flair_... | 4,568 | 35.846774 | 118 | py |
eznlp | eznlp-master/eznlp/model/encoder.py | # -*- coding: utf-8 -*-
import torch
from ..nn.init import reinit_layer_, reinit_lstm_, reinit_gru_
from ..nn.functional import mask2seq_lens
from ..nn.modules import CombinedDropout
from ..nn.modules import FeedForwardBlock, ConvBlock, TransformerEncoderBlock
from ..config import Config
class EncoderConfig(Config):... | 12,844 | 39.393082 | 135 | py |
eznlp | eznlp-master/eznlp/model/nested_embedder.py | # -*- coding: utf-8 -*-
from typing import List
from collections import Counter
import torch
from ..token import TokenSequence
from ..vocab import Vocab
from ..nn.modules import SequencePooling
from ..nn.functional import seq_lens2mask
from .embedder import OneHotConfig, OneHotEmbedder
from .encoder import EncoderConf... | 9,033 | 39.330357 | 120 | py |
eznlp | eznlp-master/eznlp/model/elmo.py | # -*- coding: utf-8 -*-
from typing import List
import torch
import allennlp.modules
from ..token import TokenSequence
from ..config import Config
class ELMoConfig(Config):
def __init__(self, **kwargs):
self.elmo: allennlp.modules.Elmo = kwargs.pop('elmo')
self.out_dim = self.elmo.get_output_dim(... | 3,732 | 32.936364 | 89 | py |
eznlp | eznlp-master/eznlp/model/model/base.py | # -*- coding: utf-8 -*-
from typing import List
import torch
from ...wrapper import Batch
from ...config import Config
class ModelConfigBase(Config):
"""Configurations of a model.
model
├─decoder
├─encoder
└─embedder
"""
_all_names = []
@property
def valid(self):
... | 2,244 | 29.753425 | 123 | py |
eznlp | eznlp-master/eznlp/model/model/classifier.py | # -*- coding: utf-8 -*-
from typing import List, Union
import torch
from ...wrapper import Batch
from ...nn.functional import mask2seq_lens
from ...config import Config, ConfigDict
from ..embedder import OneHotConfig
from ..encoder import EncoderConfig
from ..nested_embedder import SoftLexiconConfig
from ..decoder imp... | 8,091 | 36.290323 | 139 | py |
eznlp | eznlp-master/eznlp/model/model/extractor.py | # -*- coding: utf-8 -*-
from typing import List, Union
import torch
from ...wrapper import Batch
from ...nn.functional import mask2seq_lens
from ...config import Config, ConfigDict
from ..embedder import OneHotConfig
from ..encoder import EncoderConfig
from ..nested_embedder import SoftLexiconConfig
from ..decoder imp... | 9,100 | 38.398268 | 139 | py |
eznlp | eznlp-master/eznlp/model/model/specific_span_extractor.py | # -*- coding: utf-8 -*-
from typing import List, Union
from collections import OrderedDict
import torch
from ...config import ConfigList
from ...wrapper import Batch
from ..encoder import EncoderConfig
from ..decoder import (SingleDecoderConfigBase,
SpecificSpanClsDecoderConfig,
... | 5,609 | 42.153846 | 139 | py |
eznlp | eznlp-master/eznlp/model/decoder/base.py | # -*- coding: utf-8 -*-
from typing import List, Union
import torch
from ...wrapper import Batch
from ...config import Config
from ...nn.modules import SmoothLabelCrossEntropyLoss, FocalLoss
class DecoderMixinBase(object):
@property
def num_metrics(self):
return 1
def retrieve(self, batc... | 3,715 | 35.07767 | 119 | py |
eznlp | eznlp-master/eznlp/model/decoder/specific_span_sparse_rel_classification.py | # -*- coding: utf-8 -*-
from typing import List, Dict
from collections import Counter
import itertools
import logging
import copy
import math
import numpy
import torch
from ...wrapper import Batch
from ...nn.modules import CombinedDropout
from ...nn.init import reinit_embedding_, reinit_layer_, reinit_vector_parameter... | 13,869 | 49.992647 | 165 | py |
eznlp | eznlp-master/eznlp/model/decoder/boundaries.py | # -*- coding: utf-8 -*-
from typing import Union, Tuple, List
import itertools
import random
import math
import torch
from ...wrapper import TargetWrapper
from .base import SingleDecoderConfigBase, DecoderBase
MAX_SIZE_ID_COV_RATE = 0.975
def _spans_from_surrounding(span: Tuple[int], distance: int, num_tokens: int... | 12,246 | 45.744275 | 168 | py |
eznlp | eznlp-master/eznlp/model/decoder/joint_extraction.py | # -*- coding: utf-8 -*-
from typing import List, Union
import torch
from ...wrapper import Batch
from ...config import Config
from .base import DecoderMixinBase, SingleDecoderConfigBase, DecoderBase
from .sequence_tagging import SequenceTaggingDecoderConfig
from .span_classification import SpanClassificationDecoderCon... | 7,667 | 41.364641 | 96 | py |
eznlp | eznlp-master/eznlp/model/decoder/sequence_tagging.py | # -*- coding: utf-8 -*-
from typing import List
from collections import Counter
import torch
from ...wrapper import TargetWrapper, Batch
from ...utils import ChunksTagsTranslator
from ...nn.utils import unpad_seqs
from ...nn.modules import CombinedDropout, CRF
from ...nn.init import reinit_layer_
from ...metrics impor... | 6,415 | 35.044944 | 152 | py |
eznlp | eznlp-master/eznlp/model/decoder/span_attr_classification.py | # -*- coding: utf-8 -*-
from typing import List
from collections import Counter
import logging
import math
import numpy
import torch
from ...wrapper import Batch
from ...nn.modules import SequencePooling, SequenceAttention, CombinedDropout
from ...nn.functional import seq_lens2mask
from ...nn.init import reinit_embedd... | 10,352 | 43.24359 | 157 | py |
eznlp | eznlp-master/eznlp/model/decoder/specific_span_classification.py | # -*- coding: utf-8 -*-
from typing import Dict
from collections import Counter
import logging
import math
import numpy
import torch
from ...wrapper import Batch
from ...utils.chunk import detect_overlapping_level, filter_clashed_by_priority
from ...nn.modules import CombinedDropout, SoftLabelCrossEntropyLoss
from ...... | 10,413 | 47.892019 | 164 | py |
eznlp | eznlp-master/eznlp/model/decoder/text_classification.py | # -*- coding: utf-8 -*-
from typing import List
from collections import Counter
import torch
from ...wrapper import Batch
from ...nn.modules import SequencePooling, SequenceAttention, CombinedDropout
from ...nn.init import reinit_layer_
from .base import DecoderMixinBase, SingleDecoderConfigBase, DecoderBase
class T... | 4,023 | 38.067961 | 114 | py |
eznlp | eznlp-master/eznlp/model/decoder/span_rel_classification.py | # -*- coding: utf-8 -*-
from typing import List
from collections import Counter
import itertools
import logging
import math
import numpy
import torch
from ...wrapper import Batch
from ...nn.modules import SequencePooling, SequenceAttention, CombinedDropout
from ...nn.functional import seq_lens2mask
from ...nn.init imp... | 12,228 | 46.769531 | 165 | py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.