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 |
|---|---|---|---|---|---|---|
MRE-ISE | MRE-ISE-main/cores/gene/model.py | import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Variable
from torch_geometric.utils import dense_to_sparse
from cores.gene.backbone import GAT, FustionLayer, GraphLearner
from cores.lamo.decoding_network import DecoderNetwork
class MRE(nn.Module):
def __init__(self, a... | 11,439 | 47.680851 | 137 | py |
MRE-ISE | MRE-ISE-main/cores/gene/backbone.py | import math
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch import linalg as LA
from torch.autograd import Variable
from torch_geometric.utils import to_dense_adj, dense_to_sparse
from torch.distributions.relaxed_bernoulli import RelaxedBernoulli, LogitRelaxedBernoulli
from torch.distribut... | 21,984 | 43.414141 | 161 | py |
MRE-ISE | MRE-ISE-main/cores/gene/train.py | import pickle
import torch
import torch.nn as nn
from torch import optim
from tqdm import tqdm
from sklearn.metrics import classification_report
from transformers.optimization import get_linear_schedule_with_warmup
from modules.metrics import eval_result
import math
class Trainer(object):
def __init__(self, train... | 14,294 | 56.874494 | 122 | py |
DEAT | DEAT-main/preactresnet.py | '''Pre-activation ResNet in PyTorch.
Reference:
[1] Kaiming He, Xiangyu Zhang, Shaoqing Ren, Jian Sun
Identity Mappings in Deep Residual Networks. arXiv:1603.05027
'''
import torch
import torch.nn as nn
import torch.nn.functional as F
track_running_stats=True
affine=True
normal_func = nn.BatchNorm2d
# track_runn... | 7,760 | 37.044118 | 152 | py |
DEAT | DEAT-main/utils.py | import numpy as np
from collections import namedtuple
import torch
from torch import nn
import torchvision
from torch.optim.optimizer import Optimizer, required
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
################################################################
## Components from htt... | 9,103 | 34.84252 | 122 | py |
DEAT | DEAT-main/train_cifar_DEAT.py | import argparse
import logging
import sys
import time
import math
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Variable
from Positive_Negative_Momentum.pnm_optim import *
import os
from wideresnet import WideResNet
from preactresnet import PreActRe... | 40,722 | 41.287643 | 208 | py |
DEAT | DEAT-main/eval_cifar.py | import argparse
import copy
import logging
import os
import time
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from preactresnet import PreActResNet18
from wideresnet import WideResNet
from utils_plus import (upper_limit, lower_limit, std, clamp, get_loaders,
attack_pgd, ev... | 3,080 | 32.129032 | 119 | py |
DEAT | DEAT-main/utils_plus.py | #import apex.amp as amp
import torch
import torch.nn.functional as F
from torchvision import datasets, transforms
from torch.utils.data.sampler import SubsetRandomSampler
import numpy as np
upper_limit, lower_limit = 1, 0
cifar10_mean = (0.4914, 0.4822, 0.4465)
cifar10_std = (0.2471, 0.2435, 0.2616)
mu = torch.tensor... | 4,589 | 34.307692 | 106 | py |
DEAT | DEAT-main/train_cifar.py | import argparse
import logging
import sys
import time
import math
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Variable
import os
from wideresnet import WideResNet
from preactresnet import PreActResNet18, PreActResNet50
from models import *
from ut... | 39,863 | 40.962105 | 208 | py |
DEAT | DEAT-main/wideresnet.py | 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, activation='ReLU', softplus_beta=1):
super(BasicBlock, self).__init__()
self.bn1 = nn.BatchNorm2d(in_planes)
self.conv1 ... | 5,747 | 43.90625 | 141 | py |
DEAT | DEAT-main/models/shufflenetv2.py | '''ShuffleNetV2 in PyTorch.
See the paper "ShuffleNet V2: Practical Guidelines for Efficient CNN Architecture Design" for more details.
'''
import torch
import torch.nn as nn
import torch.nn.functional as F
class ShuffleBlock(nn.Module):
def __init__(self, groups=2):
super(ShuffleBlock, self).__init__()
... | 5,530 | 32.932515 | 107 | py |
DEAT | DEAT-main/models/regnet.py | '''RegNet in PyTorch.
Paper: "Designing Network Design Spaces".
Reference: https://github.com/keras-team/keras-applications/blob/master/keras_applications/efficientnet.py
'''
import torch
import torch.nn as nn
import torch.nn.functional as F
class SE(nn.Module):
'''Squeeze-and-Excitation block.'''
def __in... | 4,548 | 28.160256 | 106 | py |
DEAT | DEAT-main/models/efficientnet.py | '''EfficientNet in PyTorch.
Paper: "EfficientNet: Rethinking Model Scaling for Convolutional Neural Networks".
Reference: https://github.com/keras-team/keras-applications/blob/master/keras_applications/efficientnet.py
'''
import torch
import torch.nn as nn
import torch.nn.functional as F
def swish(x):
return x ... | 5,719 | 31.5 | 106 | py |
DEAT | DEAT-main/models/pnasnet.py | '''PNASNet in PyTorch.
Paper: Progressive Neural Architecture Search
'''
import torch
import torch.nn as nn
import torch.nn.functional as F
class SepConv(nn.Module):
'''Separable Convolution.'''
def __init__(self, in_planes, out_planes, kernel_size, stride):
super(SepConv, self).__init__()
se... | 4,258 | 32.801587 | 105 | py |
DEAT | DEAT-main/models/resnet.py | '''ResNet in PyTorch.
For Pre-activation ResNet, see 'preact_resnet.py'.
Reference:
[1] Kaiming He, Xiangyu Zhang, Shaoqing Ren, Jian Sun
Deep Residual Learning for Image Recognition. arXiv:1512.03385
'''
import torch
import torch.nn as nn
import torch.nn.functional as F
class BasicBlock(nn.Module):
expansi... | 4,218 | 30.721805 | 83 | py |
DEAT | DEAT-main/models/mobilenetv2.py | '''MobileNetV2 in PyTorch.
See the paper "Inverted Residuals and Linear Bottlenecks:
Mobile Networks for Classification, Detection and Segmentation" for more details.
'''
import torch
import torch.nn as nn
import torch.nn.functional as F
class Block(nn.Module):
'''expand + depthwise + pointwise'''
def __init... | 3,092 | 34.551724 | 114 | py |
DEAT | DEAT-main/models/vgg.py | '''VGG11/13/16/19 in Pytorch.'''
import torch
import torch.nn as nn
cfg = {
'VGG11': [64, 'M', 128, 'M', 256, 256, 'M', 512, 512, 'M', 512, 512, 'M'],
'VGG13': [64, 64, 'M', 128, 128, 'M', 256, 256, 'M', 512, 512, 'M', 512, 512, 'M'],
'VGG16': [64, 64, 'M', 128, 128, 'M', 256, 256, 256, 'M', 512, 512, 512... | 1,442 | 29.0625 | 117 | py |
DEAT | DEAT-main/models/densenet.py | '''DenseNet in PyTorch.'''
import math
import torch
import torch.nn as nn
import torch.nn.functional as F
class Bottleneck(nn.Module):
def __init__(self, in_planes, growth_rate):
super(Bottleneck, self).__init__()
self.bn1 = nn.BatchNorm2d(in_planes)
self.conv1 = nn.Conv2d(in_planes, 4*gr... | 3,542 | 31.805556 | 96 | py |
DEAT | DEAT-main/models/googlenet.py | '''GoogLeNet with PyTorch.'''
import torch
import torch.nn as nn
import torch.nn.functional as F
class Inception(nn.Module):
def __init__(self, in_planes, n1x1, n3x3red, n3x3, n5x5red, n5x5, pool_planes):
super(Inception, self).__init__()
# 1x1 conv branch
self.b1 = nn.Sequential(
... | 3,221 | 28.833333 | 83 | py |
DEAT | DEAT-main/models/resnext.py | '''ResNeXt in PyTorch.
See the paper "Aggregated Residual Transformations for Deep Neural Networks" for more details.
'''
import torch
import torch.nn as nn
import torch.nn.functional as F
class Block(nn.Module):
'''Grouped convolution block.'''
expansion = 2
def __init__(self, in_planes, cardinality=32... | 3,478 | 35.239583 | 129 | py |
DEAT | DEAT-main/models/senet.py | '''SENet in PyTorch.
SENet is the winner of ImageNet-2017. The paper is not released yet.
'''
import torch
import torch.nn as nn
import torch.nn.functional as F
class BasicBlock(nn.Module):
def __init__(self, in_planes, planes, stride=1):
super(BasicBlock, self).__init__()
self.conv1 = nn.Conv2d(... | 4,027 | 32.016393 | 102 | py |
DEAT | DEAT-main/models/shufflenet.py | '''ShuffleNet in PyTorch.
See the paper "ShuffleNet: An Extremely Efficient Convolutional Neural Network for Mobile Devices" for more details.
'''
import torch
import torch.nn as nn
import torch.nn.functional as F
class ShuffleBlock(nn.Module):
def __init__(self, groups):
super(ShuffleBlock, self).__init... | 3,542 | 31.209091 | 126 | py |
DEAT | DEAT-main/models/lenet.py | '''LeNet in PyTorch.'''
import torch.nn as nn
import torch.nn.functional as F
class LeNet(nn.Module):
def __init__(self):
super(LeNet, self).__init__()
self.conv1 = nn.Conv2d(3, 6, 5)
self.conv2 = nn.Conv2d(6, 16, 5)
self.fc1 = nn.Linear(16*5*5, 120)
self.fc2 = nn.Linear... | 699 | 28.166667 | 43 | py |
DEAT | DEAT-main/models/mobilenet.py | '''MobileNet in PyTorch.
See the paper "MobileNets: Efficient Convolutional Neural Networks for Mobile Vision Applications"
for more details.
'''
import torch
import torch.nn as nn
import torch.nn.functional as F
class Block(nn.Module):
'''Depthwise conv + Pointwise conv'''
def __init__(self, in_planes, out_... | 2,025 | 31.677419 | 123 | py |
DEAT | DEAT-main/models/dpn.py | '''Dual Path Networks in PyTorch.'''
import torch
import torch.nn as nn
import torch.nn.functional as F
class Bottleneck(nn.Module):
def __init__(self, last_planes, in_planes, out_planes, dense_depth, stride, first_layer):
super(Bottleneck, self).__init__()
self.out_planes = out_planes
sel... | 3,562 | 34.989899 | 116 | py |
DEAT | DEAT-main/Positive_Negative_Momentum/pnm_optim/pnm.py |
import math
import torch
from torch.optim.optimizer import Optimizer, required
class PNM(Optimizer):
r"""Implements Positive-Negative Momentum (PNM).
It has be proposed in
`Positive-Negative Momentum: Manipulating Stochastic Gradient Noise to Improve
Generalization`__.
Args:
params (iter... | 3,616 | 39.188889 | 121 | py |
DEAT | DEAT-main/Positive_Negative_Momentum/pnm_optim/adapnm.py |
import math
import torch
from torch.optim.optimizer import Optimizer, required
class AdaPNM(Optimizer):
r"""Implements Adaptive Positive-Negative Momentum.
It has be proposed in
`Positive-Negative Momentum: Manipulating Stochastic Gradient Noise to Improve
Generalization`__.
Arguments:
... | 5,725 | 45.177419 | 106 | py |
DEAT | DEAT-main/Positive_Negative_Momentum/model/resnet.py | '''ResNet in PyTorch.
The source code is adopted from:
https://github.com/kuangliu/pytorch-cifar
Reference:
[1] Kaiming He, Xiangyu Zhang, Shaoqing Ren, Jian Sun
Deep Residual Learning for Image Recognition. arXiv:1512.03385
'''
import torch
import torch.nn as nn
import torch.nn.functional as F
class BasicBloc... | 4,138 | 34.076271 | 102 | py |
DEAT | DEAT-main/Positive_Negative_Momentum/model/vgg.py | '''VGG11/13/16/19 in Pytorch.
The source code is adopted from:
https://github.com/kuangliu/pytorch-cifar
'''
import torch
import torch.nn as nn
cfg = {
'VGG11': [64, 'M', 128, 'M', 256, 256, 'M', 512, 512, 'M', 512, 512, 'M'],
'VGG13': [64, 64, 'M', 128, 128, 'M', 256, 256, 'M', 512, 512, 'M', 512, 512, 'M']... | 1,432 | 31.568182 | 117 | py |
DEAT | DEAT-main/Positive_Negative_Momentum/model/densenet.py | '''DenseNet in PyTorch.
The source code is adopted from:
https://github.com/kuangliu/pytorch-cifar
'''
import math
import torch
import torch.nn as nn
import torch.nn.functional as F
class Bottleneck(nn.Module):
def __init__(self, in_planes, growth_rate):
super(Bottleneck, self).__init__()
self.... | 3,707 | 33.981132 | 96 | py |
DEAT | DEAT-main/Positive_Negative_Momentum/model/googlenet.py | """google net in pytorch
The source code is adopted from:
https://github.com/weiaicunzai/pytorch-cifar100/
[1] Christian Szegedy, Wei Liu, Yangqing Jia, Pierre Sermanet, Scott Reed,
Dragomir Anguelov, Dumitru Erhan, Vincent Vanhoucke, Andrew Rabinovich.
Going Deeper with Convolutions
https://arxiv.org/a... | 4,443 | 32.164179 | 94 | py |
beta-tcvae | beta-tcvae-master/disentanglement_metrics.py | import math
import os
import torch
from tqdm import tqdm
from torch.utils.data import DataLoader
from torch.autograd import Variable
import lib.utils as utils
from metric_helpers.loader import load_model_and_dataset
from metric_helpers.mi_metric import compute_metric_shapes, compute_metric_faces
def estimate_entropi... | 8,678 | 34.863636 | 112 | py |
beta-tcvae | beta-tcvae-master/vae_quant.py | import os
import time
import math
from numbers import Number
import argparse
import torch
import torch.nn as nn
import torch.optim as optim
import visdom
from torch.autograd import Variable
from torch.utils.data import DataLoader
import lib.dist as dist
import lib.utils as utils
import lib.datasets as dset
from lib.fl... | 18,265 | 36.975052 | 120 | py |
beta-tcvae | beta-tcvae-master/plot_latent_vs_true.py | import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
import torch
from torch.autograd import Variable
from torch.utils.data import DataLoader
import brewer2mpl
bmap = brewer2mpl.get_map('Set1', 'qualitative', 3)
colors = bmap.mpl_colors
plt.style.use('ggplot')
... | 8,973 | 36.864979 | 109 | py |
beta-tcvae | beta-tcvae-master/elbo_decomposition.py | import os
import math
from numbers import Number
from tqdm import tqdm
import torch
from torch.autograd import Variable
import lib.dist as dist
import lib.flows as flows
def estimate_entropies(qz_samples, qz_params, q_dist):
"""Computes the term:
E_{p(x)} E_{q(z|x)} [-log q(z)]
and
E_{p(x)} E... | 8,303 | 34.33617 | 109 | py |
beta-tcvae | beta-tcvae-master/metric_helpers/mi_metric.py | import torch
metric_name = 'MIG'
def MIG(mi_normed):
return torch.mean(mi_normed[:, 0] - mi_normed[:, 1])
def compute_metric_shapes(marginal_entropies, cond_entropies):
factor_entropies = [6, 40, 32, 32]
mutual_infos = marginal_entropies[None] - cond_entropies
mutual_infos = torch.sort(mutual_infos... | 882 | 31.703704 | 83 | py |
beta-tcvae | beta-tcvae-master/metric_helpers/loader.py | import torch
import lib.dist as dist
import lib.flows as flows
import vae_quant
def load_model_and_dataset(checkpt_filename):
print('Loading model and dataset.')
checkpt = torch.load(checkpt_filename, map_location=lambda storage, loc: storage)
args = checkpt['args']
state_dict = checkpt['state_dict']
... | 1,550 | 33.466667 | 115 | py |
beta-tcvae | beta-tcvae-master/lib/functions.py | import torch
from torch.autograd import Function
class STHeaviside(Function):
@staticmethod
def forward(ctx, x):
y = torch.zeros(x.size()).type_as(x)
y[x >= 0] = 1
return y
@staticmethod
def backward(ctx, grad_output):
return grad_output
| 290 | 17.1875 | 44 | py |
beta-tcvae | beta-tcvae-master/lib/utils.py | from numbers import Number
import math
import torch
import os
def save_checkpoint(state, save, epoch):
if not os.path.exists(save):
os.makedirs(save)
filename = os.path.join(save, 'checkpt-%04d.pth' % epoch)
torch.save(state, filename)
class AverageMeter(object):
"""Computes and stores the a... | 1,828 | 23.716216 | 75 | py |
beta-tcvae | beta-tcvae-master/lib/datasets.py | import numpy as np
import torch
import torchvision.datasets as datasets
import torchvision.transforms as transforms
class Shapes(object):
def __init__(self, dataset_zip=None):
loc = 'data/dsprites_ndarray_co1sh3sc6or40x32y32_64x64.npz'
if dataset_zip is None:
self.dataset_zip = np.loa... | 1,102 | 22.978261 | 75 | py |
beta-tcvae | beta-tcvae-master/lib/dist.py | import math
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Variable
from lib.functions import STHeaviside
eps = 1e-8
class Normal(nn.Module):
"""Samples from a Normal distribution using the reparameterization trick.
"""
def __init__(self,... | 8,542 | 32.501961 | 84 | py |
beta-tcvae | beta-tcvae-master/lib/flows.py | import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Variable
from lib.dist import Normal
eps = 1e-8
class FactorialNormalizingFlow(nn.Module):
def __init__(self, dim, nsteps):
super(FactorialNormalizingFlow, self).__init__()
self.dim = dim
self.... | 1,405 | 30.244444 | 94 | py |
gunpowder | gunpowder-master/gunpowder/__init__.py | from __future__ import absolute_import
from .nodes import *
from .array import Array, ArrayKey, ArrayKeys
from .array_spec import ArraySpec
from .batch import Batch
from .batch_request import BatchRequest
from .build import build
from .coordinate import Coordinate
from .graph import Graph, Node, Edge, GraphKey, Graph... | 648 | 27.217391 | 57 | py |
gunpowder | gunpowder-master/gunpowder/torch/nodes/predict.py | from gunpowder.array import ArrayKey, Array
from gunpowder.array_spec import ArraySpec
from gunpowder.ext import torch
from gunpowder.nodes.generic_predict import GenericPredict
import logging
from typing import Dict, Union
logger = logging.getLogger(__name__)
class Predict(GenericPredict):
"""Torch implementat... | 5,622 | 34.815287 | 83 | py |
gunpowder | gunpowder-master/gunpowder/torch/nodes/train.py | import logging
import numpy as np
from gunpowder.array import ArrayKey, Array
from gunpowder.array_spec import ArraySpec
from gunpowder.ext import torch, tensorboardX, NoSuchModule
from gunpowder.nodes.generic_train import GenericTrain
from typing import Dict, Union, Optional
logger = logging.getLogger(__name__)
c... | 13,024 | 36.002841 | 96 | py |
gunpowder | gunpowder-master/gunpowder/jax/generic_jax_model.py | class GenericJaxModel:
"""An interface for models to follow in order to train or predict. A model
implementing this interface will need to contain not only the forward
model but also loss and update fn. Some examples can be found in
https://github.com/funkelab/funlib.learn.jax
Args:
is_tra... | 2,633 | 25.34 | 78 | py |
gunpowder | gunpowder-master/gunpowder/jax/__init__.py | from .generic_jax_model import GenericJaxModel
from .nodes import *
| 68 | 22 | 46 | py |
gunpowder | gunpowder-master/gunpowder/jax/nodes/predict.py | from gunpowder.array import ArrayKey, Array
from gunpowder.array_spec import ArraySpec
from gunpowder.ext import jax
from gunpowder.nodes.generic_predict import GenericPredict
from gunpowder.jax import GenericJaxModel
import pickle
import logging
from typing import Dict, Union
logger = logging.getLogger(__name__)
c... | 3,564 | 32.317757 | 88 | py |
gunpowder | gunpowder-master/gunpowder/jax/nodes/train.py | import logging
import numpy as np
from gunpowder.ext import jax
from gunpowder.ext import jnp
import pickle
import os
from gunpowder.array import ArrayKey, Array
from gunpowder.array_spec import ArraySpec
from gunpowder.ext import tensorboardX, NoSuchModule
from gunpowder.nodes.generic_train import GenericTrain
from g... | 11,796 | 36.690096 | 99 | py |
gunpowder | gunpowder-master/gunpowder/ext/__init__.py | from __future__ import print_function
import logging
import traceback
import sys
logger = logging.getLogger(__name__)
class NoSuchModule(object):
def __init__(self, name):
self.__name = name
self.__traceback_str = traceback.format_tb(sys.exc_info()[2])
errtype, value = sys.exc_info()[:2]... | 1,676 | 17.228261 | 69 | py |
gunpowder | gunpowder-master/tests/cases/jax_train.py | from .provider_test import ProviderTest
from gunpowder import (
BatchProvider,
BatchRequest,
ArraySpec,
Roi,
Coordinate,
ArrayKeys,
ArrayKey,
Array,
Batch,
Scan,
PreCache,
build,
)
from gunpowder.ext import jax, haiku, optax, NoSuchModule
from gunpowder.jax import Train, ... | 8,810 | 31.274725 | 84 | py |
gunpowder | gunpowder-master/tests/cases/torch_train.py | from .provider_test import ProviderTest
from gunpowder import (
BatchProvider,
BatchRequest,
ArraySpec,
Roi,
Coordinate,
ArrayKeys,
ArrayKey,
Array,
Batch,
Scan,
PreCache,
build,
)
from gunpowder.ext import torch, NoSuchModule
from gunpowder.torch import Train, Predict
fr... | 9,228 | 29.259016 | 81 | py |
gunpowder | gunpowder-master/docs/build/conf.py | # -*- coding: utf-8 -*-
#
# gunpowder documentation build configuration file, created by
# sphinx-quickstart on Fri Jun 30 12:59:21 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.
#
#... | 5,592 | 30.24581 | 245 | py |
treelstm.pytorch | treelstm.pytorch-master/main.py | from __future__ import division
from __future__ import print_function
import os
import random
import logging
import torch
import torch.nn as nn
import torch.optim as optim
# IMPORT CONSTANTS
from treelstm import Constants
# NEURAL NETWORK MODULES/LAYERS
from treelstm import SimilarityTreeLSTM
# DATA HANDLING CLASSES... | 7,610 | 39.484043 | 99 | py |
treelstm.pytorch | treelstm.pytorch-master/treelstm/utils.py | from __future__ import division
from __future__ import print_function
import os
import math
import torch
from .vocab import Vocab
# loading GLOVE word vectors
# if .pth file is found, will load that
# else will load from .txt file & save
def load_word_vectors(path):
if os.path.isfile(path + '.pth') and os.path... | 2,376 | 32.957143 | 89 | py |
treelstm.pytorch | treelstm.pytorch-master/treelstm/model.py | import torch
import torch.nn as nn
import torch.nn.functional as F
from . import Constants
# module for childsumtreelstm
class ChildSumTreeLSTM(nn.Module):
def __init__(self, in_dim, mem_dim):
super(ChildSumTreeLSTM, self).__init__()
self.in_dim = in_dim
self.mem_dim = mem_dim
sel... | 3,286 | 36.352273 | 95 | py |
treelstm.pytorch | treelstm.pytorch-master/treelstm/dataset.py | import os
from tqdm import tqdm
from copy import deepcopy
import torch
import torch.utils.data as data
from . import Constants
from .tree import Tree
# Dataset class for SICK dataset
class SICKDataset(data.Dataset):
def __init__(self, path, vocab, num_classes):
super(SICKDataset, self).__init__()
... | 2,927 | 32.655172 | 82 | py |
treelstm.pytorch | treelstm.pytorch-master/treelstm/metrics.py | from copy import deepcopy
import torch
class Metrics():
def __init__(self, num_classes):
self.num_classes = num_classes
def pearson(self, predictions, labels):
x = deepcopy(predictions)
y = deepcopy(labels)
x = (x - x.mean()) / x.std()
y = (y - y.mean()) / y.std()
... | 504 | 23.047619 | 43 | py |
treelstm.pytorch | treelstm.pytorch-master/treelstm/trainer.py | from tqdm import tqdm
import torch
from . import utils
class Trainer(object):
def __init__(self, args, model, criterion, optimizer, device):
super(Trainer, self).__init__()
self.args = args
self.model = model
self.criterion = criterion
self.optimizer = optimizer
s... | 2,384 | 40.842105 | 96 | py |
FastVae_Gpu | FastVae_Gpu-main/run_mm.py | from dataloader import RecData, UserItemData
from sampler_gpu_mm import SamplerBase, PopularSampler, MidxUniform, MidxUniPop
import torch
import torch.optim
from torch.optim.lr_scheduler import StepLR
from torch.utils.data import DataLoader
from vae_models import BaseVAE, VAE_Sampler
import argparse
import numpy as np
... | 10,590 | 45.862832 | 172 | py |
FastVae_Gpu | FastVae_Gpu-main/vae_models.py | import torch
import torch.nn as nn
import torch.nn.functional as F
import time
class BaseVAE(nn.Module):
def __init__(self, num_item, dims, active='relu', dropout=0.5):
"""
dims is a list for latent dims
"""
super(BaseVAE, self).__init__()
self.num_item = num_item
... | 6,596 | 38.740964 | 115 | py |
FastVae_Gpu | FastVae_Gpu-main/dataloader.py | import pandas as pd
from torch.utils.data import IterableDataset, Dataset
import torch
from torch.utils.data import Dataset, IterableDataset, DataLoader
import scipy.io as sci
import scipy as sp
import random
import numpy as np
import math
import os
class RecData(object):
def __init__(self, dir, file_name):
... | 3,526 | 35.739583 | 96 | py |
FastVae_Gpu | FastVae_Gpu-main/utils.py | import scipy as sp
import scipy.sparse as ss
import scipy.io as sio
import random
import numpy as np
from typing import List
import logging
import torch
import math
from torch.nn.utils.rnn import pad_sequence
def get_logger(filename, verbosity=1, name=None):
filename = filename + '.txt'
level_dict = {0: loggi... | 10,977 | 41.550388 | 166 | py |
FastVae_Gpu | FastVae_Gpu-main/sampler_gpu_mm.py | # The cluster algorithmn(K-means) is implemented on the GPU
from operator import imod, neg
from numpy.core.numeric import indices
import scipy.sparse as sps
from sklearn import cluster
from sklearn.cluster import KMeans
import torch
import numpy as np
import torch.nn as nn
from torch._C import device, dtype
def kmean... | 12,583 | 40.668874 | 163 | py |
KSTER | KSTER-main/test/unit/test_decoder.py | from torch.nn import GRU, LSTM
import torch
from joeynmt.decoders import RecurrentDecoder
from joeynmt.encoders import RecurrentEncoder
from .test_helpers import TensorTestCase
class TestRecurrentDecoder(TensorTestCase):
def setUp(self):
self.emb_size = 10
self.num_layers = 3
self.hidden... | 12,263 | 51.187234 | 80 | py |
KSTER | KSTER-main/test/unit/test_loss.py | import torch
from joeynmt.loss import XentLoss
from .test_helpers import TensorTestCase
class TestTransformerUtils(TensorTestCase):
def setUp(self):
seed = 42
torch.manual_seed(seed)
def test_label_smoothing(self):
pad_index = 0
smoothing = 0.4
criterion = XentLoss(p... | 3,037 | 34.325581 | 78 | py |
KSTER | KSTER-main/test/unit/test_weight_tying.py | from torch.nn import GRU, LSTM
import torch
import numpy as np
from joeynmt.encoders import RecurrentEncoder
from .test_helpers import TensorTestCase
from joeynmt.model import build_model
from joeynmt.vocabulary import Vocabulary
import copy
class TestWeightTying(TensorTestCase):
def setUp(self):
self.s... | 3,861 | 34.759259 | 77 | py |
KSTER | KSTER-main/test/unit/test_transformer_utils.py | import torch
from joeynmt.transformer_layers import PositionalEncoding
from .test_helpers import TensorTestCase
class TestTransformerUtils(TensorTestCase):
def setUp(self):
seed = 42
torch.manual_seed(seed)
def test_position_encoding(self):
batch_size = 2
max_time = 3
... | 595 | 23.833333 | 66 | py |
KSTER | KSTER-main/test/unit/test_batch.py | import torch
import random
from torchtext.data.batch import Batch as TorchTBatch
from joeynmt.batch import Batch
from joeynmt.data import load_data, make_data_iter
from joeynmt.constants import PAD_TOKEN
from .test_helpers import TensorTestCase
class TestData(TensorTestCase):
def setUp(self):
self.trai... | 5,692 | 40.554745 | 80 | py |
KSTER | KSTER-main/test/unit/test_model_init.py | from torch.nn import GRU, LSTM
import torch
from torch import nn
import numpy as np
from joeynmt.encoders import RecurrentEncoder
from .test_helpers import TensorTestCase
from joeynmt.model import build_model
from joeynmt.vocabulary import Vocabulary
import copy
class TestModelInit(TensorTestCase):
def setUp(se... | 1,962 | 31.180328 | 75 | py |
KSTER | KSTER-main/test/unit/test_encoder.py | from torch.nn import GRU, LSTM
import torch
from joeynmt.encoders import RecurrentEncoder
from .test_helpers import TensorTestCase
class TestRecurrentEncoder(TensorTestCase):
def setUp(self):
self.emb_size = 10
self.num_layers = 3
self.hidden_size = 7
seed = 42
torch.manu... | 5,086 | 45.669725 | 79 | py |
KSTER | KSTER-main/test/unit/test_search.py | import torch
import numpy as np
from joeynmt.search import greedy, recurrent_greedy, transformer_greedy
from joeynmt.search import beam_search
from joeynmt.decoders import RecurrentDecoder, TransformerDecoder
from joeynmt.encoders import RecurrentEncoder
from joeynmt.embeddings import Embeddings
from joeynmt.model imp... | 8,723 | 39.018349 | 83 | py |
KSTER | KSTER-main/test/unit/test_transformer_decoder.py | import torch
from joeynmt.decoders import TransformerDecoder, TransformerDecoderLayer
from .test_helpers import TensorTestCase
class TestTransformerDecoder(TensorTestCase):
def setUp(self):
self.emb_size = 12
self.num_layers = 3
self.hidden_size = 12
self.ff_size = 24
sel... | 6,322 | 42.909722 | 79 | py |
KSTER | KSTER-main/test/unit/test_transformer_encoder.py | import torch
from joeynmt.encoders import TransformerEncoder
from .test_helpers import TensorTestCase
class TestTransformerEncoder(TensorTestCase):
def setUp(self):
self.emb_size = 12
self.num_layers = 3
self.hidden_size = 12
self.ff_size = 24
self.num_heads = 4
s... | 3,144 | 40.381579 | 78 | py |
KSTER | KSTER-main/test/unit/test_embeddings.py | import torch
from joeynmt.embeddings import Embeddings
from .test_helpers import TensorTestCase
class TestEmbeddings(TensorTestCase):
def setUp(self):
self.emb_size = 10
self.vocab_size = 11
self.pad_idx = 1
seed = 42
torch.manual_seed(seed)
def test_size(self):
... | 3,091 | 38.139241 | 78 | py |
KSTER | KSTER-main/test/unit/test_attention.py | import torch
from joeynmt.attention import BahdanauAttention, LuongAttention
from .test_helpers import TensorTestCase
class TestBahdanauAttention(TensorTestCase):
def setUp(self):
self.key_size = 3
self.query_size = 5
self.hidden_size = 7
seed = 42
torch.manual_seed(seed)... | 16,419 | 42.786667 | 81 | py |
KSTER | KSTER-main/test/unit/test_helpers.py | import unittest
import torch
class TensorTestCase(unittest.TestCase):
def assertTensorNotEqual(self, expected, actual):
equal = torch.equal(expected, actual)
if equal:
self.fail("Tensors did match but weren't supposed to: expected {},"
" actual {}.".format(expect... | 879 | 34.2 | 79 | py |
KSTER | KSTER-main/scripts/average_checkpoints.py | #!/usr/bin/env python3
# coding: utf-8
"""
Checkpoint averaging
Mainly follows:
https://github.com/pytorch/fairseq/blob/master/scripts/average_checkpoints.py
"""
import argparse
import collections
import torch
from typing import List
def average_checkpoints(inputs: List[str]) -> dict:
"""Loads checkpoints fro... | 3,018 | 30.123711 | 79 | py |
KSTER | KSTER-main/docs/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,375 | 28.377049 | 79 | py |
KSTER | KSTER-main/joeynmt/vocabulary.py | # coding: utf-8
"""
Vocabulary module
"""
from collections import defaultdict, Counter
from typing import List
import numpy as np
from torchtext.data import Dataset
from joeynmt.constants import UNK_TOKEN, DEFAULT_UNK_ID, \
EOS_TOKEN, BOS_TOKEN, PAD_TOKEN
class Vocabulary:
""" Vocabulary represents mapping... | 6,887 | 33.09901 | 79 | py |
KSTER | KSTER-main/joeynmt/build_database.py | import torch
import numpy as np
import logging
from hashlib import md5
from joeynmt.prediction import parse_test_args
from joeynmt.helpers import load_config, load_checkpoint, get_latest_checkpoint
from joeynmt.data import load_data, Dataset, make_data_iter
from joeynmt.model import build_model, _DataParallel, Model
... | 7,739 | 39.52356 | 119 | py |
KSTER | KSTER-main/joeynmt/prediction.py | # coding: utf-8
"""
This modules holds methods for generating predictions from a model.
"""
import os
import sys
from typing import List, Optional
import logging
import numpy as np
import json
import torch
from torchtext.data import Dataset, Field
from joeynmt.helpers import bpe_postprocess, check_combiner_cfg, load_... | 32,482 | 41.406005 | 239 | py |
KSTER | KSTER-main/joeynmt/batch.py | # coding: utf-8
"""
Implementation of a mini-batch.
"""
import torch
class Batch:
"""Object for holding a batch of data with mask during training.
Input is a batch from a torch text iterator.
"""
# pylint: disable=too-many-instance-attributes
def __init__(self, torch_batch, pad_index, use_cuda=Fa... | 3,327 | 32.616162 | 73 | py |
KSTER | KSTER-main/joeynmt/loss.py | # coding: utf-8
"""
Module to implement training loss
"""
import torch
from torch import nn, Tensor
from torch.autograd import Variable
class XentLoss(nn.Module):
"""
Cross-Entropy Loss with optional label smoothing
"""
def __init__(self, pad_index: int, smoothing: float = 0.0):
super().__in... | 3,120 | 38.506329 | 78 | py |
KSTER | KSTER-main/joeynmt/embeddings.py | # coding: utf-8
"""
Embedding module
"""
import io
import math
import logging
import torch
from torch import nn, Tensor
from joeynmt.helpers import freeze_params
from joeynmt.vocabulary import Vocabulary
logger = logging.getLogger(__name__)
class Embeddings(nn.Module):
"""
Simple embeddings class
"""
... | 4,157 | 33.363636 | 80 | py |
KSTER | KSTER-main/joeynmt/training.py | # coding: utf-8
"""
Training module
"""
import argparse
import time
import shutil
from typing import List
import logging
import os
import sys
import collections
import pathlib
import numpy as np
import torch
from torch import Tensor
from torch.utils.tensorboard import SummaryWriter
from torchtext.data import Dataset... | 33,649 | 40.389914 | 80 | py |
KSTER | KSTER-main/joeynmt/model.py | # coding: utf-8
"""
Module to represents whole models
"""
from typing import Callable
import logging
import torch.nn as nn
from torch import Tensor
import torch.nn.functional as F
from joeynmt.initialization import initialize_model
from joeynmt.embeddings import Embeddings
from joeynmt.encoders import Encoder, Recurr... | 12,260 | 37.800633 | 80 | py |
KSTER | KSTER-main/joeynmt/data.py | # coding: utf-8
"""
Data module
"""
import sys
import random
import os
import os.path
from typing import Optional
import logging
from torchtext.datasets import TranslationDataset
from torchtext import data
from torchtext.data import Dataset, Iterator, Field
from joeynmt.constants import UNK_TOKEN, EOS_TOKEN, BOS_TOKE... | 9,111 | 37.774468 | 79 | py |
KSTER | KSTER-main/joeynmt/transformer_layers.py | # -*- coding: utf-8 -*-
import math
import torch
import torch.nn as nn
from torch import Tensor
# pylint: disable=arguments-differ
class MultiHeadedAttention(nn.Module):
"""
Multi-Head Attention module from "Attention is All You Need"
Implementation modified from OpenNMT-py.
https://github.com/OpenN... | 10,131 | 32.66113 | 80 | py |
KSTER | KSTER-main/joeynmt/initialization.py | # coding: utf-8
"""
Implements custom initialization
"""
import math
import torch
import torch.nn as nn
from torch import Tensor
from torch.nn.init import _calculate_fan_in_and_fan_out
def orthogonal_rnn_init_(cell: nn.RNNBase, gain: float = 1.):
"""
Orthogonal initialization of recurrent weights
RNN p... | 6,419 | 35.271186 | 79 | py |
KSTER | KSTER-main/joeynmt/builders.py | # coding: utf-8
"""
Collection of builder functions
"""
from typing import Callable, Optional, Generator
import torch
from torch import nn
from torch.optim.lr_scheduler import _LRScheduler, ReduceLROnPlateau, \
StepLR, ExponentialLR
from torch.optim import Optimizer
from joeynmt.helpers import ConfigurationError
... | 12,622 | 38.446875 | 80 | py |
KSTER | KSTER-main/joeynmt/combiners.py | import torch
from torch import nn
import torch.nn.functional as F
from torch.nn import init
import numpy as np
import math
from typing import Tuple
from joeynmt.database import Database, EnhancedDatabase
from joeynmt.kernel import Kernel, GaussianKernel, LaplacianKernel
class Combiner(nn.Module):
def __init__(se... | 11,897 | 46.214286 | 140 | py |
KSTER | KSTER-main/joeynmt/search.py | # coding: utf-8
import torch
import torch.nn.functional as F
from torch import Tensor
import numpy as np
from joeynmt.decoders import TransformerDecoder
from joeynmt.model import Model
from joeynmt.batch import Batch
from joeynmt.helpers import tile
__all__ = ["greedy", "transformer_greedy", "beam_search", "run_batch... | 18,708 | 39.321121 | 88 | py |
KSTER | KSTER-main/joeynmt/attention.py | # coding: utf-8
"""
Attention modules
"""
import torch
from torch import Tensor
import torch.nn as nn
import torch.nn.functional as F
class AttentionMechanism(nn.Module):
"""
Base attention class
"""
def forward(self, *inputs):
raise NotImplementedError("Implement this.")
class BahdanauAtt... | 7,824 | 33.933036 | 80 | py |
KSTER | KSTER-main/joeynmt/helpers.py | # coding: utf-8
"""
Collection of helper functions
"""
import copy
import glob
import os
import os.path
import errno
import shutil
import random
import logging
from typing import Optional, List
import pathlib
import numpy as np
import pkg_resources
import torch
from torch import nn, Tensor
from torch.utils.tensorboard... | 14,240 | 32.587264 | 122 | py |
KSTER | KSTER-main/joeynmt/combiner_training.py | # coding: utf-8
"""
Training module
"""
import argparse
import time
import shutil
from typing import List
import logging
import os
import sys
import collections
import pathlib
import numpy as np
import torch
from torch import Tensor
from torch.utils.tensorboard import SummaryWriter
from torchtext.data import Dataset... | 34,477 | 40.893074 | 89 | py |
KSTER | KSTER-main/joeynmt/decoders.py | # coding: utf-8
"""
Various decoders
"""
from typing import Optional
import torch
import torch.nn as nn
from torch import Tensor
from joeynmt.attention import BahdanauAttention, LuongAttention
from joeynmt.encoders import Encoder
from joeynmt.helpers import freeze_params, ConfigurationError, subsequent_mask
from joey... | 23,155 | 40.647482 | 80 | py |
KSTER | KSTER-main/joeynmt/encoders.py | # coding: utf-8
import torch
import torch.nn as nn
from torch import Tensor
from torch.nn.utils.rnn import pack_padded_sequence, pad_packed_sequence
from joeynmt.helpers import freeze_params
from joeynmt.transformer_layers import \
TransformerEncoderLayer, PositionalEncoding
#pylint: disable=abstract-method
cla... | 8,571 | 36.432314 | 80 | py |
KSTER | KSTER-main/joeynmt/kernel.py | import torch
from typing import Tuple, Union
class Kernel(object):
def __init__(self) -> None:
super(Kernel, self).__init__()
def similarity(self, distances: torch.Tensor, bandwidth: Union[float, torch.Tensor]) -> torch.Tensor:
raise NotImplementedError
def compute_example_based_dist... | 1,423 | 40.882353 | 143 | py |
AT-on-AD | AT-on-AD-main/test_fmnist.py | import argparse
import logging
import numpy as np
import os
import os.path as osp
import torch
import torch.nn as nn
class MyLR(nn.Module):
def __init__(self, input_size, num_classes):
super(MyLR, self).__init__()
self.linear = nn.Linear(input_size, num_classes)
def forward(self, x):
... | 3,685 | 28.023622 | 182 | py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.