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 |
|---|---|---|---|---|---|---|
pytorch-seq2seq | pytorch-seq2seq-master/tests/test_loss_loss.py | import math
import random
import unittest
import torch
import torch.nn.functional as F
from torch.autograd import Variable
from seq2seq.loss.loss import Loss
from seq2seq.loss import NLLLoss, Perplexity
class TestLoss(unittest.TestCase):
@classmethod
def setUpClass(cls):
num_class = 5
batch_s... | 2,819 | 31.790698 | 85 | py |
pytorch-seq2seq | pytorch-seq2seq-master/tests/test_predictor.py | import os
import unittest
import torchtext
from seq2seq.evaluator import Predictor
from seq2seq.dataset import SourceField, TargetField
from seq2seq.models import Seq2seq, EncoderRNN, DecoderRNN
class TestPredictor(unittest.TestCase):
@classmethod
def setUpClass(self):
test_path = os.path.dirname(os... | 1,137 | 32.470588 | 93 | py |
pytorch-seq2seq | pytorch-seq2seq-master/tests/test_encoder_rnn.py | import os
import unittest
import torch
from torch.autograd import Variable
from seq2seq.models import EncoderRNN
class TestEncoderRNN(unittest.TestCase):
@classmethod
def setUpClass(self):
self.vocab_size = 100
self.input_var = Variable(torch.randperm(self.vocab_size).view(10, 10))
se... | 2,697 | 37.542857 | 85 | py |
pytorch-seq2seq | pytorch-seq2seq-master/docs/source/conf.py | # -*- coding: utf-8 -*-
#
# pytorch-seq2seq documentation build configuration file, created by
# sphinx-quickstart on Tue Jun 27 14:35:26 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 fil... | 5,613 | 30.016575 | 97 | py |
pytorch-seq2seq | pytorch-seq2seq-master/seq2seq/trainer/supervised_trainer.py | from __future__ import division
import logging
import os
import random
import time
import torch
import torchtext
from torch import optim
import seq2seq
from seq2seq.evaluator import Evaluator
from seq2seq.loss import NLLLoss
from seq2seq.optim import Optimizer
from seq2seq.util.checkpoint import Checkpoint
class Sup... | 8,130 | 42.25 | 129 | py |
pytorch-seq2seq | pytorch-seq2seq-master/seq2seq/dataset/fields.py | import logging
import torchtext
class SourceField(torchtext.data.Field):
""" Wrapper class of torchtext.data.Field that forces batch_first and include_lengths to be True. """
def __init__(self, **kwargs):
logger = logging.getLogger(__name__)
if kwargs.get('batch_first') is False:
... | 1,950 | 37.254902 | 151 | py |
pytorch-seq2seq | pytorch-seq2seq-master/seq2seq/models/seq2seq.py | import torch.nn as nn
import torch.nn.functional as F
class Seq2seq(nn.Module):
""" Standard sequence-to-sequence architecture with configurable encoder
and decoder.
Args:
encoder (EncoderRNN): object of EncoderRNN
decoder (DecoderRNN): object of DecoderRNN
decode_function (func, o... | 3,067 | 54.781818 | 121 | py |
pytorch-seq2seq | pytorch-seq2seq-master/seq2seq/models/baseRNN.py | """ A base class for RNN. """
import torch.nn as nn
class BaseRNN(nn.Module):
r"""
Applies a multi-layer RNN to an input sequence.
Note:
Do not use this class directly, use one of the sub classes.
Args:
vocab_size (int): size of the vocabulary
max_len (int): maximum allowed len... | 1,714 | 34 | 105 | py |
pytorch-seq2seq | pytorch-seq2seq-master/seq2seq/models/DecoderRNN.py | import random
import numpy as np
import torch
import torch.nn as nn
from torch.autograd import Variable
import torch.nn.functional as F
from .attention import Attention
from .baseRNN import BaseRNN
if torch.cuda.is_available():
import torch.cuda as device
else:
import torch as device
class DecoderRNN(Base... | 9,851 | 45.253521 | 135 | py |
pytorch-seq2seq | pytorch-seq2seq-master/seq2seq/models/TopKDecoder.py | import torch
import torch.nn.functional as F
from torch.autograd import Variable
def _inflate(tensor, times, dim):
"""
Given a tensor, 'inflates' it along the given dimension by replicating each slice specified number of times (in-place)
Args:
tensor: A :class:`Tensor` to inflate
... | 16,819 | 48.181287 | 136 | py |
pytorch-seq2seq | pytorch-seq2seq-master/seq2seq/models/EncoderRNN.py | import torch.nn as nn
from .baseRNN import BaseRNN
class EncoderRNN(BaseRNN):
r"""
Applies a multi-layer RNN to an input sequence.
Args:
vocab_size (int): size of the vocabulary
max_len (int): a maximum allowed length for the sequence to be processed
hidden_size (int): the number ... | 3,943 | 50.894737 | 130 | py |
pytorch-seq2seq | pytorch-seq2seq-master/seq2seq/models/attention.py | import torch
import torch.nn as nn
import torch.nn.functional as F
class Attention(nn.Module):
r"""
Applies an attention mechanism on the output features from the decoder.
.. math::
\begin{array}{ll}
x = context*output \\
attn = exp(x_i) / sum_j exp(x_j) \\
... | 2,660 | 35.452055 | 118 | py |
pytorch-seq2seq | pytorch-seq2seq-master/seq2seq/evaluator/predictor.py | import torch
from torch.autograd import Variable
class Predictor(object):
def __init__(self, model, src_vocab, tgt_vocab):
"""
Predictor class to evaluate for a given model.
Args:
model (seq2seq.models): trained model. This can be loaded from a checkpoint
using... | 2,514 | 32.986486 | 96 | py |
pytorch-seq2seq | pytorch-seq2seq-master/seq2seq/evaluator/evaluator.py | from __future__ import print_function, division
import torch
import torchtext
import seq2seq
from seq2seq.loss import NLLLoss
class Evaluator(object):
""" Class to evaluate models with given datasets.
Args:
loss (seq2seq.loss, optional): loss for evaluator (default: seq2seq.loss.NLLLoss)
bat... | 2,424 | 33.642857 | 121 | py |
pytorch-seq2seq | pytorch-seq2seq-master/seq2seq/util/checkpoint.py | from __future__ import print_function
import os
import time
import shutil
import torch
import dill
class Checkpoint(object):
"""
The Checkpoint class manages the saving and loading of a model during training. It allows training to be suspended
and resumed at a later time (e.g. when running on a cluster us... | 5,328 | 40.632813 | 129 | py |
pytorch-seq2seq | pytorch-seq2seq-master/seq2seq/optim/optim.py | import itertools
import torch
class Optimizer(object):
""" The Optimizer class encapsulates torch.optim package and provides functionalities
for learning rate scheduling and gradient norm clipping.
Args:
optim (torch.optim.Optimizer): optimizer object, the parameters to be optimized
s... | 1,994 | 35.944444 | 110 | py |
pytorch-seq2seq | pytorch-seq2seq-master/seq2seq/loss/loss.py | from __future__ import print_function
import math
import torch.nn as nn
import numpy as np
class Loss(object):
""" Base class for encapsulation of the loss functions.
This class defines interfaces that are commonly used with loss functions
in training and inferencing. For information regarding individual... | 5,297 | 34.086093 | 96 | py |
GRCN | GRCN-master/dataprocess.py | import numpy as np
import torch
from collections import defaultdict
from torch_scatter import scatter_add
class Data(object):
def __init__(self, x, y, adj, train_mask, val_mask, test_mask):
self.x = x
self.y = y
self.num_nodes = x.shape[0]
self.adj = adj
self.train_mask = t... | 6,800 | 43.743421 | 108 | py |
GRCN | GRCN-master/main_ours.py | import argparse
import glob
import logging
import sys
import os
import torch
from torch_scatter import scatter_add
from tqdm import tqdm
import torch.nn.functional as F
import torch.nn as nn
from torch_geometric.nn import GCNConv
from complete import Complete, convert_edge2adj, normalize, _complete_acc
from utils impor... | 8,697 | 41.019324 | 120 | py |
GRCN | GRCN-master/utils.py | import torch
import torch.nn as nn
import os, shutil
import numpy as np
from torch_geometric.datasets import Planetoid, CoraFull, Amazon, Coauthor
import scipy.sparse as sp
def load_dataset(name):
if name in ["Cora", "CiteSeer", "PubMed"]:
dataset = Planetoid(root='./data/'+name, name=name)
elif name ... | 1,870 | 32.410714 | 87 | py |
GRCN | GRCN-master/complete.py | '''
Complete the graph structrue
Be careful that the completed graph should be symmetric
Be careful that you need to renormalize the completed adjacency matrix
'''
import torch
from tqdm import tqdm
import torch.nn.functional as F
from torch_geometric.nn import GCNConv
from sklearn.metrics.pairwise import *
from collec... | 3,941 | 36.903846 | 107 | py |
GRCN | GRCN-master/config/config_Cora.py | import torch
import torch.nn.functional as F
params_fixed={
"nhid": 32, # number of hidden units per layer
"dropout": 0.5,
"F": torch.relu,
"F_graph": torch.tanh,
"lr": 5e-3, # learning rate for node classification
"wd": 5e-3, # weight decay for node classification
"lr_graph": 1e-3, # learn... | 952 | 27.878788 | 60 | py |
GRCN | GRCN-master/config/config_CiteSeer.py | import torch
import torch.nn.functional as F
params_fixed={
"nhid": 32, # number of hidden units per layer
"dropout": 0.5,
"F": torch.relu,
"F_graph": torch.tanh,
"lr": 5e-2, # learning rate for node classification
"wd": 5e-3, # weight decay for node classification
"lr_graph": 1e-3, # learn... | 954 | 27.939394 | 60 | py |
GRCN | GRCN-master/config/config_CoraFull.py | import torch
import torch.nn.functional as F
params_random={
"nhid": 64, # number of hidden units per layer
"dropout": 0.5,
"F": torch.relu,
"F_graph": "identity",
"lr": 5e-3, # learning rate for node classification
"wd": 5e-3, # weight decay for node classification
"lr_graph": 5e-3, # lear... | 501 | 26.888889 | 60 | py |
GRCN | GRCN-master/config/config_Computers.py | import torch
import torch.nn.functional as F
params_random={
"nhid": 64, # number of hidden units per layer
"dropout": 0.5,
"F": torch.relu,
"F_graph": torch.tanh,
"lr": 5e-3, # learning rate for node classification
"wd": 5e-3, # weight decay for node classification, default 5e-3
"lr_graph"... | 515 | 27.666667 | 68 | py |
GRCN | GRCN-master/config/config_PubMed.py | import torch
import torch.nn.functional as F
params_fixed={
"nhid": 32, # number of hidden units per layer
"dropout": 0.5,
"F": torch.relu,
"F_graph": torch.tanh,
"lr": 5e-3, # learning rate for node classification
"wd": 5e-3, # weight decay for node classification
"lr_graph": 0, # learning... | 954 | 27.939394 | 60 | py |
GRCN | GRCN-master/config/config_CS.py | import torch
import torch.nn.functional as F
params_random={
"nhid": 64, # number of hidden units per layer
"dropout": 0.5,
"F": torch.relu,
"F_graph": torch.tanh,
"lr": 5e-3, # learning rate for node classification
"wd": 5e-3, # weight decay for node classification, default 5e-3
"lr_graph"... | 515 | 27.666667 | 68 | py |
GRCN | GRCN-master/models/GRCN_fast.py | import torch
import torch.nn as nn
import torch.nn.functional as F
from torch_geometric.nn import GCNConv, SGConv, GATConv, knn_graph
from sklearn.neighbors import kneighbors_graph
from sklearn.metrics.pairwise import rbf_kernel
import numpy as np
from .model_utils import GCNConv_diag, GCNConv_dense, EOS
import torch_s... | 6,789 | 45.506849 | 141 | py |
GRCN | GRCN-master/models/model_utils.py | import torch
import torch.nn as nn
import torch.nn.functional as F
from torch_geometric.nn import GCNConv, SGConv, GATConv, knn_graph
from sklearn.neighbors import kneighbors_graph
from sklearn.metrics.pairwise import rbf_kernel
import numpy as np
EOS = 1e-10
class GCNConv_dense(torch.nn.Module):
'''
A GCN c... | 2,668 | 29.678161 | 95 | py |
GRCN | GRCN-master/models/GRCN.py | import torch
import torch.nn as nn
import torch.nn.functional as F
from torch_geometric.nn import GCNConv, SGConv, GATConv, knn_graph
from sklearn.neighbors import kneighbors_graph
from sklearn.metrics.pairwise import rbf_kernel
import numpy as np
from .model_utils import GCNConv_diag, GCNConv_dense, EOS
import torch_s... | 6,356 | 45.065217 | 141 | py |
PLATON | PLATON-main/Pruner.py | import os
import sys
import argparse
import logging
import random
import torch
import numpy as np
class Pruner(object):
def __init__(self, model, args, total_step, tb_writer=None, \
mask_param_name=['attention.self', 'attention.output.dense',\
'output.dense', 'intermediate.dense']... | 6,043 | 44.104478 | 111 | py |
PLATON | PLATON-main/SQuAD/Pruner.py | import os
import sys
import argparse
import logging
import random
import torch
import numpy as np
class Pruner(object):
def __init__(self, model, args, total_step, tb_writer=None, \
mask_param_name=['attention.self', 'attention.output.dense',\
'output.dense', 'intermediate.dense']... | 6,043 | 44.104478 | 111 | py |
PLATON | PLATON-main/SQuAD/run_squad.py | # coding=utf-8
# Copyright 2018 The Google AI Language Team Authors and The HuggingFace Inc. team.
# Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a cop... | 37,923 | 41.997732 | 134 | py |
PLATON | PLATON-main/GLUE/eval.py | # coding=utf-8
# Copyright (c) Microsoft. All rights reserved.
import argparse
import json
import os
import random
from datetime import datetime
from pprint import pprint
import numpy as np
import torch
from torch.utils.data import Dataset, DataLoader, BatchSampler
from pretrained_models import *
from tensorboardX impo... | 24,590 | 49.703093 | 217 | py |
PLATON | PLATON-main/GLUE/predict.py | import argparse
from ast import arg
import json
import os
import torch
from torch.utils.data import DataLoader
from data_utils.task_def import TaskType
from experiments.exp_def import TaskDefs, EncoderModelType
from torch.utils.data import Dataset, DataLoader, BatchSampler
from mt_dnn.batcher import SingleTaskDataset,... | 3,405 | 27.383333 | 84 | py |
PLATON | PLATON-main/GLUE/train.py | # coding=utf-8
# Copyright (c) Microsoft. All rights reserved.
import argparse
import json
import pickle
import os
import random
from datetime import datetime
from pprint import pprint
import numpy as np
import torch
from torch.utils.data import Dataset, DataLoader, BatchSampler
from pretrained_models import *
from ten... | 30,197 | 50.444634 | 131 | py |
PLATON | PLATON-main/GLUE/mt_dnn/inference.py | # coding=utf-8
# Copyright (c) Microsoft. All rights reserved.
from data_utils.metrics import calc_metrics
from mt_dnn.batcher import Collater
from data_utils.task_def import TaskType
import torch
from tqdm import tqdm
def extract_encoding(model, data, use_cuda=True):
if use_cuda:
model.cuda()
sequence... | 1,948 | 38.77551 | 120 | py |
PLATON | PLATON-main/GLUE/mt_dnn/prune_model_new.py | # coding=utf-8
# Copyright (c) Microsoft. All rights reserved.
import copy
import os
import sys
import torch
import tasks
import logging
import numpy as np
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torch.optim.lr_scheduler import *
from data_utils.utils import AverageMeter
f... | 30,670 | 48.62945 | 193 | py |
PLATON | PLATON-main/GLUE/mt_dnn/batcher.py | # coding=utf-8
# Copyright (c) Microsoft. All rights reserved.
import sys
import json
import torch
import random
import numpy as np
from shutil import copyfile
from data_utils.task_def import TaskType, DataFormat
from data_utils.task_def import EncoderModelType
import tasks
from torch.utils.data import Dataset, DataLoa... | 24,573 | 43.437613 | 147 | py |
PLATON | PLATON-main/GLUE/mt_dnn/perturbation.py | # Copyright (c) Microsoft. All rights reserved.
from copy import deepcopy
import torch
import logging
import random
from torch.nn import Parameter
from functools import wraps
import torch.nn.functional as F
from data_utils.task_def import TaskType
from data_utils.task_def import EncoderModelType
from .loss import stabl... | 4,380 | 39.564815 | 139 | py |
PLATON | PLATON-main/GLUE/mt_dnn/matcher.py | # coding=utf-8
# Copyright (c) Microsoft. All rights reserved.
import os
import torch
import torch.nn as nn
from pretrained_models import MODEL_CLASSES
from module.dropout_wrapper import DropoutWrapper
from module.san import SANClassifier, MaskLmHeader
from module.san_model import SanModel
from module.pooler import Poo... | 7,766 | 46.944444 | 170 | py |
PLATON | PLATON-main/GLUE/mt_dnn/loss.py | # coding=utf-8
# Copyright (c) Microsoft. All rights reserved.
import torch
from torch.nn.modules.loss import _Loss
import torch.nn.functional as F
import torch.nn as nn
from enum import IntEnum
def stable_kl(logit, target, epsilon=1e-6, reduce=True):
logit = logit.view(-1, logit.size(-1)).float()
target = ta... | 9,530 | 34.169742 | 156 | py |
PLATON | PLATON-main/GLUE/mt_dnn/model.py | # coding=utf-8
# Copyright (c) Microsoft. All rights reserved.
import copy
import os
import sys
import torch
import tasks
import logging
import numpy as np
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torch.optim.lr_scheduler import *
from data_utils.utils import AverageMeter
f... | 29,903 | 48.59204 | 193 | py |
PLATON | PLATON-main/GLUE/mt_dnn/prune_model.py | # coding=utf-8
# Copyright (c) Microsoft. All rights reserved.
import copy
import os
import sys
import torch
import tasks
import logging
import numpy as np
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torch.optim.lr_scheduler import *
from data_utils.utils import AverageMeter
f... | 31,293 | 48.28189 | 191 | py |
PLATON | PLATON-main/GLUE/module/san_model.py | import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.nn.parameter import Parameter
import copy
from pytorch_pretrained_bert.modeling import BertEmbeddings, BertLayerNorm, BertConfig
from module.similarity import SelfAttnWrapper
from module.dropout_wrapper import DropoutWrapper
class SanLayer(n... | 4,792 | 39.618644 | 124 | py |
PLATON | PLATON-main/GLUE/module/my_optim.py | # coding=utf-8
# Copyright (c) Microsoft. All rights reserved.
from copy import deepcopy
import torch
from torch.nn import Parameter
from functools import wraps
class EMA:
def __init__(self, gamma, model):
super(EMA, self).__init__()
self.gamma = gamma
self.shadow = {}
self.model = ... | 3,851 | 33.088496 | 94 | py |
PLATON | PLATON-main/GLUE/module/pooler.py | import torch.nn as nn
from module.common import activation
from module.dropout_wrapper import DropoutWrapper
class Pooler(nn.Module):
def __init__(self, hidden_size, dropout_p=0.1, actf='tanh'):
super(Pooler, self).__init__()
self.dense = nn.Linear(hidden_size, hidden_size)
self.activation ... | 686 | 39.411765 | 64 | py |
PLATON | PLATON-main/GLUE/module/modeling_bert_masked.py | # coding=utf-8
# Copyright 2018 The Google AI Language Team Authors and The HuggingFace Inc. team.
# Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a cop... | 9,551 | 46.054187 | 130 | py |
PLATON | PLATON-main/GLUE/module/bert_optim.py | # coding=utf-8
# Copyright (c) Microsoft. All rights reserved.
import math
import torch
from torch.optim import Optimizer
from torch.nn.utils import clip_grad_norm_
from pytorch_pretrained_bert.optimization import warmup_constant, warmup_cosine, warmup_linear
from typing import Callable, Iterable, Tuple
def warmup_lin... | 47,999 | 45.153846 | 190 | py |
PLATON | PLATON-main/GLUE/module/similarity.py | # coding=utf-8
# Copyright (c) Microsoft. All rights reserved.
import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy
from torch.nn.utils import weight_norm
from torch.nn.parameter import Parameter
from .common import activation, init_wrapper
from .dropout_wrapper import DropoutWrapper
class D... | 23,237 | 39.984127 | 135 | py |
PLATON | PLATON-main/GLUE/module/dropout_wrapper.py | # coding=utf-8
# Copyright (c) Microsoft. All rights reserved.
import torch
import torch.nn as nn
import torch.nn.functional as F
class DropoutWrapper(nn.Module):
"""
This is a dropout wrapper which supports the fix mask dropout
"""
def __init__(self, dropout_p=0, enable_vbp=True):
super(Dropou... | 1,089 | 33.0625 | 130 | py |
PLATON | PLATON-main/GLUE/module/common.py | # coding=utf-8
# Copyright (c) Microsoft. All rights reserved.
import torch
import math
from torch.nn.functional import tanh, relu, prelu, leaky_relu, sigmoid, elu, selu
from torch.nn.init import uniform, normal, eye, xavier_uniform, xavier_normal, kaiming_uniform, kaiming_normal, orthogonal
def linear(x):
return ... | 797 | 22.470588 | 122 | py |
PLATON | PLATON-main/GLUE/module/sub_layers.py | # coding=utf-8
# Copyright (c) Microsoft. All rights reserved.
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.nn.parameter import Parameter
class LayerNorm(nn.Module):
#ref: https://github.com/pytorch/pytorch/issues/1959
# :https://arxiv.org/pdf/1607.06450.pdf
def __init__(... | 920 | 31.892857 | 95 | py |
PLATON | PLATON-main/GLUE/module/san.py | # coding=utf-8
# Copyright (c) Microsoft. All rights reserved.
import torch
import random
import torch.nn as nn
from torch.nn.utils import weight_norm
from torch.nn.parameter import Parameter
import torch.nn.functional as F
from module.dropout_wrapper import DropoutWrapper
from module.similarity import FlatSimilarityWr... | 5,299 | 40.40625 | 134 | py |
PLATON | PLATON-main/GLUE/experiments/squad/squad_utils.py | import os
import six
import json
import string
import collections
import torch.nn.functional as F
import numpy as np
import torch
import math
from data_utils.task_def import EncoderModelType
from pytorch_pretrained_bert.tokenization import BertTokenizer
LARGE_NEG_NUM = -1.0e5
tokenizer = None
def remove_punc(text):
... | 21,715 | 37.778571 | 207 | py |
PLATON | PLATON-main/GLUE/experiments/squad/verify_calc_span.py | from pytorch_pretrained_bert import BertTokenizer
from data_utils.task_def import EncoderModelType
from experiments.squad.squad_utils import calc_tokenized_span_range, parse_squad_label
model = "bert-base-uncased"
do_lower_case = True
tokenizer = BertTokenizer.from_pretrained(model, do_lower_case=do_lower_case)
for n... | 751 | 46 | 116 | py |
PLATON | PLATON-main/GLUE/tasks/__init__.py | import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
from data_utils.task_def import TaskType
from module.san import SANClassifier
TASK_REGISTRY = {}
TASK_CLASS_NAMES = set()
class MTDNNTask:
def __init__(self, task_def):
self._task_def = task_def
def input_parse_labe... | 4,370 | 28.14 | 118 | py |
PLATON | PLATON-main/GLUE/data_utils/utils.py | # Copyright (c) Microsoft. All rights reserved.
import random
import torch
import numpy
import subprocess
class AverageMeter(object):
"""Computes and stores the average and current value."""
def __init__(self):
self.reset()
def reset(self):
self.val = 0
self.avg = 0
self.su... | 1,244 | 24.408163 | 66 | py |
Bubblewrap | Bubblewrap-main/bubblewrap.py | import numpy
import jax.numpy as np
from math import floor
import time
from collections import deque
from jax import jit, grad, vmap, value_and_grad
import jax.scipy.stats
from jax.scipy.stats import multivariate_normal as jmvn
from scipy.stats import multivariate_normal as mvn
from jax.scipy.special import logsumexp a... | 14,300 | 30.993289 | 218 | py |
Bubblewrap | Bubblewrap-main/datagen.py | import sys
from typing import Callable, Optional
import numpy as np
from scipy.integrate import solve_ivp
from tqdm import trange
def lorenz(t, y: np.ndarray, s=10., r=28., b=2.667):
"""
copy & pasted here in order to avoid importing jax, which doesn't run on M1 macs
"""
x_dot = s * (y[1] - y[0])
... | 5,107 | 32.168831 | 152 | py |
Bubblewrap | Bubblewrap-main/models/kernels.py | from functools import wraps
import jax.numpy as np
from jax.numpy import exp, sqrt
from jax.numpy.linalg import norm
# From https://docs.pymc.io/api/gp/cov.html.
def normalize(func):
@wraps(func)
def wrapper(*args, ϵ=1e-7, **kwargs):
res = func(*args, **kwargs)
return res / (ϵ + np.sum(res, ... | 1,336 | 22.051724 | 78 | py |
Bubblewrap | Bubblewrap-main/models/logprob.py | import os
import sys
import numpy as np
import scipy.io as sio
import torch
from scipy.special import logsumexp
from scipy.stats import multivariate_normal
from tqdm import trange
from vjf import online
def import_lorenz_vdp(filename):
data = np.load(filename)
xs = data['x'] # state
ys = data['y'] # o... | 4,782 | 31.537415 | 123 | py |
VNL_Estimation | VNL_Estimation-main/VNL_Monocular_Depth_Prediction/tools/train_nyu_metric.py | from data.load_dataset import CustomerDataLoader
from lib.utils.training_stats import TrainingStats
from lib.utils.evaluate_depth_error import validate_err
from lib.models.metric_depth_model import *
from lib.core.config import cfg, merge_cfg_from_file, print_configs
from lib.utils.net_tools import save_ckpt, load_ckpt... | 5,796 | 36.160256 | 119 | py |
VNL_Estimation | VNL_Estimation-main/VNL_Monocular_Depth_Prediction/tools/test_nyu_metric.py | import os
import cv2
import torch
import numpy as np
from lib.core.config import cfg
from lib.utils.net_tools import load_ckpt
from tools.parse_arg_test import TestOptions
from lib.core.config import merge_cfg_from_file
from data.load_dataset import CustomerDataLoader
from lib.models.image_transfer import resize_image
... | 4,249 | 47.295455 | 122 | py |
VNL_Estimation | VNL_Estimation-main/VNL_Monocular_Depth_Prediction/tools/train_kitti_metric.py | from data.load_dataset import CustomerDataLoader
from lib.utils.training_stats import TrainingStats
from lib.utils.evaluate_depth_error import validate_err_kitti
from lib.models.metric_depth_model import *
from lib.core.config import cfg, merge_cfg_from_file, print_configs
from lib.utils.net_tools import save_ckpt, loa... | 5,614 | 37.724138 | 148 | py |
VNL_Estimation | VNL_Estimation-main/VNL_Monocular_Depth_Prediction/tools/test_kitti_metric.py | import os
import cv2
import torch
import numpy as np
import matplotlib.pyplot as plt
from lib.core.config import cfg
from lib.utils.net_tools import load_ckpt
from tools.parse_arg_test import TestOptions
from lib.core.config import merge_cfg_from_file
from data.load_dataset import CustomerDataLoader
from lib.utils.eval... | 4,235 | 48.255814 | 175 | py |
VNL_Estimation | VNL_Estimation-main/VNL_Monocular_Depth_Prediction/tools/recover_surface_normal.py | import torch
import numpy as np
import torch.nn as nn
def init_image_coor(height, width):
x_row = np.arange(0, width)
x = np.tile(x_row, (height, 1))
x = x[np.newaxis, :, :]
x = x.astype(np.float32)
x = torch.from_numpy(x.copy()).cuda()
u_u0 = x - width/2.0
y_col = np.arange(0, height) #... | 5,598 | 39.868613 | 142 | py |
VNL_Estimation | VNL_Estimation-main/VNL_Monocular_Depth_Prediction/tools/test_any_images.py | import os
import cv2
import torch
import numpy as np
from lib.utils.net_tools import load_ckpt
from lib.utils.logging import setup_logging
import torchvision.transforms as transforms
from tools.parse_arg_test import TestOptions
from data.load_dataset import CustomerDataLoader
from lib.models.metric_depth_model import M... | 2,338 | 33.397059 | 121 | py |
VNL_Estimation | VNL_Estimation-main/VNL_Monocular_Depth_Prediction/data/load_dataset.py | import torch.utils.data
import importlib
from lib.utils.logging import setup_logging
logger = setup_logging(__name__)
class CustomerDataLoader():
def __init__(self, opt):
self.opt = opt
self.dataset = create_dataset(opt)
self.dataloader = torch.utils.data.DataLoader(
self.datase... | 1,657 | 30.283019 | 94 | py |
VNL_Estimation | VNL_Estimation-main/VNL_Monocular_Depth_Prediction/data/nyudv2_dataset.py | import cv2
import json
import torch
import os.path
import numpy as np
import scipy.io as sio
from lib.core.config import cfg
import torchvision.transforms as transforms
from lib.utils.logging import setup_logging
logger = setup_logging(__name__)
class NYUDV2Dataset():
def initialize(self, opt):
self.opt ... | 7,144 | 38.258242 | 140 | py |
VNL_Estimation | VNL_Estimation-main/VNL_Monocular_Depth_Prediction/data/kitti_dataset.py | import cv2
import json
import torch
import os.path
import numpy as np
from lib.core.config import cfg
import torchvision.transforms as transforms
from lib.utils.logging import setup_logging
logger = setup_logging(__name__)
class KITTIDataset():
def initialize(self, opt):
self.opt = opt
self.root ... | 9,252 | 41.251142 | 136 | py |
VNL_Estimation | VNL_Estimation-main/VNL_Monocular_Depth_Prediction/data/any_dataset.py | import cv2
import json
import torch
import os.path
import numpy as np
import scipy.io as sio
from lib.core.config import cfg
import torchvision.transforms as transforms
from lib.utils.logging import setup_logging
logger = setup_logging(__name__)
class ANYDataset():
def initialize(self, opt):
self.data_si... | 424 | 16.708333 | 43 | py |
VNL_Estimation | VNL_Estimation-main/VNL_Monocular_Depth_Prediction/lib/models/ResNeXt.py | from collections import OrderedDict
import torch.nn as nn
from lib.core.config import cfg
# ---------------------------------------------------------------------------- #
# Bits for specific architectures (ResNeXt50, ResNeXt101, ...)
# ---------------------------------------------------------------------------- #
def... | 5,460 | 37.457746 | 131 | py |
VNL_Estimation | VNL_Estimation-main/VNL_Monocular_Depth_Prediction/lib/models/VNL_loss.py | import torch
import torch.nn as nn
import numpy as np
class VNL_Loss(nn.Module):
"""
Virtual Normal Loss Function.
"""
def __init__(self, focal_x, focal_y, input_size,
delta_cos=0.867, delta_diff_x=0.01,
delta_diff_y=0.01, delta_diff_z=0.01,
delta_z=0... | 8,198 | 41.046154 | 121 | py |
VNL_Estimation | VNL_Estimation-main/VNL_Monocular_Depth_Prediction/lib/models/lateral_net.py | import torch
import torch.nn as nn
from lib.core.config import cfg
import lib.models.ResNeXt as ResNeXt
import lib.utils.resnext_weights_helper as resnext_utils
import lib.utils.mobilenetv2_weight_helper as mobilenet_utils
import lib.models.MobileNetV2 as MobileNetV2
from torch.nn import functional as F
import math
de... | 12,525 | 38.765079 | 138 | py |
VNL_Estimation | VNL_Estimation-main/VNL_Monocular_Depth_Prediction/lib/models/image_transfer.py | import torch
import cv2
from lib.core.config import cfg
import numpy as np
import torch.nn.functional as F
def bins_to_depth(depth_bin):
"""
Transfer n-channel discrate depth bins to 1-channel conitnuous depth
:param depth_bin: n-channel output of the network, [b, c, h, w]
:return: 1-channel depth, [b,... | 1,973 | 37.705882 | 133 | py |
VNL_Estimation | VNL_Estimation-main/VNL_Monocular_Depth_Prediction/lib/models/metric_depth_model.py | import torch
import torch.nn as nn
import numpy as np
from . import lateral_net as lateral_net
from lib.utils.net_tools import get_func
from lib.models.WCEL_loss import WCEL_Loss
from lib.models.VNL_loss import VNL_Loss
from lib.models.image_transfer import bins_to_depth, kitti_merge_imgs
from lib.core.config import cf... | 5,365 | 35.503401 | 135 | py |
VNL_Estimation | VNL_Estimation-main/VNL_Monocular_Depth_Prediction/lib/models/MobileNetV2.py | import torch.nn as nn
import math
from lib.core.config import cfg
# ---------------------------------------------------------------------------- #
# Bits for specific architectures (ResNeXt50, ResNeXt101, ...)
# ---------------------------------------------------------------------------- #
def MobileNetV2_body():
r... | 5,474 | 34.322581 | 129 | py |
VNL_Estimation | VNL_Estimation-main/VNL_Monocular_Depth_Prediction/lib/models/WCEL_loss.py | import torch
import torch.nn as nn
import numpy as np
from lib.core.config import cfg
class WCEL_Loss(nn.Module):
"""
Weighted Cross-entropy Loss Function.
"""
def __init__(self):
super(WCEL_Loss, self).__init__()
self.weight = cfg.DATASET.WCE_LOSS_WEIGHT
self.weight /= np.sum(... | 1,169 | 39.344828 | 108 | py |
VNL_Estimation | VNL_Estimation-main/VNL_Monocular_Depth_Prediction/lib/utils/mobilenetv2_weight_helper.py | import os
import torch
from lib.core.config import cfg
import numpy as np
import logging
logger = logging.getLogger(__name__)
def load_pretrained_imagenet_resnext_weights(model):
"""Load pretrained weights
Args:
num_layers: 50 for res50 and so on.
model: the generalized rcnnn module
"""
... | 1,656 | 35.021739 | 127 | py |
VNL_Estimation | VNL_Estimation-main/VNL_Monocular_Depth_Prediction/lib/utils/resnext_weights_helper.py | import os
import torch
from lib.core.config import cfg
import logging
logger = logging.getLogger(__name__)
def load_pretrained_imagenet_resnext_weights(model):
"""Load pretrained weights
Args:
num_layers: 50 for res50 and so on.
model: the generalized rcnnn module
"""
weights_file = os.... | 1,828 | 34.173077 | 123 | py |
VNL_Estimation | VNL_Estimation-main/VNL_Monocular_Depth_Prediction/lib/utils/net_tools.py | import os
import dill
import torch
import importlib
import torch.nn as nn
from lib.core.config import cfg
from lib.utils.logging import setup_logging
logger = setup_logging(__name__)
def get_func(func_name):
"""Helper to return a function object by name. func_name must identify a
function in this module or t... | 2,512 | 34.394366 | 110 | py |
VNL_Estimation | VNL_Estimation-main/VNL_Monocular_Depth_Prediction/lib/utils/evaluate_depth_error.py | import logging
import torch
import numpy as np
logger = logging.getLogger(__name__)
def recover_metric_depth(pred, gt):
if type(pred).__module__ == torch.__name__:
pred = pred.cpu().numpy()
if type(gt).__module__ == torch.__name__:
gt = gt.cpu().numpy()
gt_mean = np.mean(gt)
gt_var = ... | 10,696 | 33.506452 | 103 | py |
kymatio | kymatio-master/benchmarks/benchmarks/scattering3d.py | import torch
import kymatio.scattering3d.backend as backend
from kymatio import HarmonicScattering3D
class BenchmarkHarmonicScattering3D:
params = [
[
{ # Small. 32x32x32, 2 scales, 2 harmonics
"J": 2,
"shape": (32, 32, 32),
"L": 2,
},... | 1,480 | 28.039216 | 80 | py |
kymatio | kymatio-master/benchmarks/benchmarks/scattering1d.py | import torch
import kymatio.scattering1d.backend as backend
from kymatio import Scattering1D
class BenchmarkScattering1D:
params = [
[
{ # Typical of EEG. J=8, Q=1, N=1024
# See Warrick et al. Physiological Measurement 2019
"J": 8,
"Q": 1,
... | 1,332 | 25.137255 | 65 | py |
kymatio | kymatio-master/benchmarks/benchmarks/scattering2d.py | import torch
import kymatio.scattering2d.backend as backend
from kymatio import Scattering2D
class BenchmarkScattering2D:
params = [
[
{ # MNIST-like. 32x32, 2 scales, 8 orientations
"J": 2,
"shape": (32, 32),
"L": 8,
},
{ ... | 1,303 | 26.166667 | 72 | py |
kymatio | kymatio-master/benchmarks/benchmarks/common.py | import torch
torch.manual_seed(0)
| 34 | 10.666667 | 20 | py |
kymatio | kymatio-master/kymatio/torch.py | from .scattering1d.frontend.torch_frontend import ScatteringTorch1D as Scattering1D
from .scattering2d.frontend.torch_frontend import ScatteringTorch2D as Scattering2D
from .scattering3d.frontend.torch_frontend \
import HarmonicScatteringTorch3D as HarmonicScattering3D
Scattering1D.__module__ = 'kymatio.torch'... | 616 | 37.5625 | 83 | py |
kymatio | kymatio-master/kymatio/keras.py | from .scattering1d.frontend.keras_frontend \
import ScatteringKeras1D as Scattering1D
from .scattering2d.frontend.keras_frontend \
import ScatteringKeras2D as Scattering2D
Scattering1D.__module__ = 'kymatio.keras'
Scattering1D.__name__ = 'Scattering1D'
Scattering2D.__module__ = 'kymatio.keras'
Scattering2D.__... | 388 | 28.923077 | 44 | py |
kymatio | kymatio-master/kymatio/scattering1d/utils.py | import numpy as np
import math
from .filter_bank import scattering_filter_factory, calibrate_scattering_filters
def compute_border_indices(J, i0, i1):
"""
Computes border indices at all scales which correspond to the original
signal boundaries after padding.
At the finest resolution,
original_sign... | 9,757 | 33.85 | 81 | py |
kymatio | kymatio-master/kymatio/scattering1d/core/scattering1d.py | # Authors: Mathieu Andreux, Joakim Anden, Edouard Oyallon
# Scientific Ancestry: Joakim Anden, Mathieu Andreux, Vincent Lostanlen
def scattering1d(x, pad, unpad, backend, J, psi1, psi2, phi, pad_left=0,
pad_right=0, ind_start=None, ind_end=None, oversampling=0,
max_order=2, average=True, size_scatteri... | 6,716 | 34.539683 | 94 | py |
kymatio | kymatio-master/kymatio/scattering1d/backend/torch_backend.py | # Authors: Edouard Oyallon, Joakim Anden, Mathieu Andreux
import torch
import torch.nn.functional as F
from collections import namedtuple
from packaging import version
BACKEND_NAME = 'torch'
from ...backend.torch_backend import _is_complex, Modulus, concatenate, type_checks, cdgmm, real
from ...backend.base_backend... | 5,184 | 32.025478 | 120 | py |
kymatio | kymatio-master/kymatio/scattering1d/backend/torch_skcuda_backend.py | # Authors: Edouard Oyallon, Joakim Anden
import torch
import cupy
from collections import namedtuple
from string import Template
BACKEND_NAME = 'torch_skcuda'
# As of v8, cupy.util has been renamed cupy._util.
if hasattr(cupy, '_util'):
memoize = cupy._util.memoize
else:
memoize = cupy.util.memoize
@memoize... | 7,616 | 30.475207 | 120 | py |
kymatio | kymatio-master/kymatio/scattering1d/frontend/base_frontend.py | from ...frontend.base_frontend import ScatteringBase
import math
import numbers
import numpy as np
from ..filter_bank import scattering_filter_factory
from ..utils import (compute_border_indices, compute_padding, compute_minimum_support_to_pad,
compute_meta_scattering, precompute_size_scattering)
class ScatteringBa... | 16,209 | 42.575269 | 120 | py |
kymatio | kymatio-master/kymatio/scattering1d/frontend/keras_frontend.py | from ...frontend.keras_frontend import ScatteringKeras
from ...scattering1d.frontend.base_frontend import ScatteringBase1D
from kymatio.tensorflow import Scattering1D as ScatteringTensorFlow1D
from tensorflow.python.framework import tensor_shape
class ScatteringKeras1D(ScatteringKeras, ScatteringBase1D):
def __... | 1,430 | 39.885714 | 75 | py |
kymatio | kymatio-master/kymatio/scattering1d/frontend/torch_frontend.py | # Authors: Mathieu Andreux, Joakim Anden, Edouard Oyallon
# Scientific Ancestry: Joakim Anden, Mathieu Andreux, Vincent Lostanlen
import torch
import warnings
from ...frontend.torch_frontend import ScatteringTorch
from ..core.scattering1d import scattering1d
from ..utils import precompute_size_scattering
from .base_f... | 5,908 | 38.393333 | 126 | py |
kymatio | kymatio-master/kymatio/backend/base_backend.py |
class FFT:
def __init__(self, fft, ifft, irfft, type_checks):
self.fft = fft
self.ifft = ifft
self.irfft = irfft
self.sanity_checks = type_checks
def fft_forward(self, x, direction='C2C', inverse=False):
"""Interface with FFT routines for any dimensional signals and an... | 1,755 | 28.762712 | 91 | py |
kymatio | kymatio-master/kymatio/backend/torch_backend.py | from torch.autograd import Function
import torch
BACKEND_NAME = 'torch'
def input_checks(x):
if x is None:
raise TypeError('The input should be not empty.')
if not x.is_contiguous():
raise RuntimeError('The input must be contiguous.')
def _is_complex(x):
return x.shape[-1] == 2
def _is_... | 7,023 | 27.552846 | 82 | py |
kymatio | kymatio-master/kymatio/backend/torch_skcuda_backend.py | import torch
from skcuda import cublas
BACKEND_NAME = 'torch_skcuda'
def _is_complex(x):
return x.shape[-1] == 2
def _is_real(x):
return x.shape[-1] == 1
def cdgmm(A, B, inplace=False):
"""Complex pointwise multiplication.
Complex pointwise multiplication between (batched) tensor A and tens... | 2,819 | 30.685393 | 103 | py |
kymatio | kymatio-master/kymatio/frontend/entry.py | import logging
import warnings
import importlib
class ScatteringEntry(object):
def __init__(self, *args, **kwargs):
self.name = kwargs['name']
self.class_name = kwargs['class_name']
kwargs.pop('name')
kwargs.pop('class_name')
frontend_suffixes = {'torch' : 'Torch',
... | 2,078 | 34.844828 | 114 | py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.