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 |
|---|---|---|---|---|---|---|
DaVinci | DaVinci-main/taming/modules/vqvae/quantize.py | import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
from torch import einsum
from einops import rearrange
class VectorQuantizer(nn.Module):
"""
see https://github.com/MishaLaskin/vqvae/blob/d761a999e2267766400dc646d82d3ac3657771d4/models/quantizer.py
_____________________... | 13,259 | 39.181818 | 110 | py |
DaVinci | DaVinci-main/taming/modules/discriminator/model.py | import functools
import torch.nn as nn
from taming.modules.util import ActNorm
def weights_init(m):
classname = m.__class__.__name__
if classname.find('Conv') != -1:
nn.init.normal_(m.weight.data, 0.0, 0.02)
elif classname.find('BatchNorm') != -1:
nn.init.normal_(m.weight.data, 1.0, 0.02... | 2,550 | 36.514706 | 116 | py |
DaVinci | DaVinci-main/taming/modules/misc/coord.py | import torch
class CoordStage(object):
def __init__(self, n_embed, down_factor):
self.n_embed = n_embed
self.down_factor = down_factor
def eval(self):
return self
def encode(self, c):
"""fake vqmodel interface"""
assert 0.0 <= c.min() and c.max() <= 1.0
b,c... | 904 | 27.28125 | 79 | py |
DaVinci | DaVinci-main/taming/modules/diffusionmodules/model.py | # pytorch_diffusion + derived encoder decoder
import math
import torch
import torch.nn as nn
import numpy as np
def get_timestep_embedding(timesteps, embedding_dim):
"""
This matches the implementation in Denoising Diffusion Probabilistic Models:
From Fairseq.
Build sinusoidal embeddings.
This mat... | 30,221 | 37.895753 | 121 | py |
DaVinci | DaVinci-main/taming/modules/transformer/mingpt.py | """
taken from: https://github.com/karpathy/minGPT/
GPT model:
- the initial stem consists of a combination of token encoding and a positional encoding
- the meat of it is a uniform sequence of Transformer blocks
- each Transformer is a sequential combination of a 1-hidden-layer MLP block and a self-attention block... | 16,836 | 39.473558 | 140 | py |
DaVinci | DaVinci-main/taming/modules/transformer/permuter.py | import torch
import torch.nn as nn
import numpy as np
class AbstractPermuter(nn.Module):
def __init__(self, *args, **kwargs):
super().__init__()
def forward(self, x, reverse=False):
raise NotImplementedError
class Identity(AbstractPermuter):
def __init__(self):
super().__init__()... | 7,093 | 27.48996 | 83 | py |
DaVinci | DaVinci-main/taming/modules/losses/lpips.py | """Stripped version of https://github.com/richzhang/PerceptualSimilarity/tree/master/models"""
import torch
import torch.nn as nn
from torchvision import models
from collections import namedtuple
from taming.util import get_ckpt_path
class LPIPS(nn.Module):
# Learned perceptual metric
def __init__(self, use... | 4,836 | 38.008065 | 104 | py |
DaVinci | DaVinci-main/taming/modules/losses/segmentation.py | import torch.nn as nn
import torch.nn.functional as F
class BCELoss(nn.Module):
def forward(self, prediction, target):
loss = F.binary_cross_entropy_with_logits(prediction,target)
return loss, {}
class BCELossWithQuant(nn.Module):
def __init__(self, codebook_weight=1.):
super().__ini... | 816 | 34.521739 | 82 | py |
DaVinci | DaVinci-main/taming/modules/losses/vqperceptual.py | import torch
import torch.nn as nn
import torch.nn.functional as F
from taming.modules.losses.lpips import LPIPS
from taming.modules.discriminator.model import NLayerDiscriminator, weights_init
class DummyLoss(nn.Module):
def __init__(self):
super().__init__()
def adopt_weight(weight, global_step, thre... | 6,179 | 44.109489 | 113 | py |
DaVinci | DaVinci-main/taming/models/vqgan.py | import torch
import torch.nn.functional as F
import pytorch_lightning as pl
from taming.main import instantiate_from_config
from taming.modules.diffusionmodules.model import Encoder, Decoder
from taming.modules.vqvae.quantize import VectorQuantizer2 as VectorQuantizer
from taming.modules.vqvae.quantize import GumbelQ... | 14,908 | 39.958791 | 120 | py |
DaVinci | DaVinci-main/taming/models/cond_transformer.py | import os, math
import torch
import torch.nn.functional as F
import pytorch_lightning as pl
from taming.main import instantiate_from_config
from taming.modules.util import SOSProvider
def disabled_train(self, mode=True):
"""Overwrite model.train with this function to make sure train/eval mode
does not change... | 15,002 | 42.613372 | 127 | py |
HeadlineCause | HeadlineCause-main/headline_cause/labse.py | import gc
import numpy as np
import tensorflow as tf
import tensorflow_hub as hub
import tensorflow_text as text
from tqdm import tqdm
from util import gen_batch
DEFAULT_ENCODER_PATH = "https://tfhub.dev/google/LaBSE/2"
DEFAULT_PREPROCESSOR_PATH = "https://tfhub.dev/google/universal-sentence-encoder-cmlm/multilingual... | 1,380 | 33.525 | 112 | py |
HeadlineCause | HeadlineCause-main/headline_cause/util.py | import os
import json
import csv
import random
from urllib.parse import urlparse
import torch
import numpy as np
def write_tsv(records, header, path):
with open(path, "w") as w:
writer = csv.writer(w, delimiter="\t", quotechar='"')
writer.writerow(header)
for r in records:
row... | 1,720 | 23.585714 | 67 | py |
HeadlineCause | HeadlineCause-main/headline_cause/predict.py | import argparse
import torch
from tqdm import tqdm
from transformers import AutoModelForSequenceClassification, AutoTokenizer, pipeline
import numpy as np
from util import read_jsonl, write_jsonl
def get_batch(data, batch_size):
start_index = 0
while start_index < len(data):
end_index = start_index ... | 1,850 | 31.473684 | 103 | py |
HeadlineCause | HeadlineCause-main/headline_cause/train_clf.py | import argparse
import json
import random
from statistics import mean
import torch
from torch.utils.data import Dataset
from transformers import AutoTokenizer, AutoModelForSequenceClassification
from transformers import Trainer, TrainingArguments, EarlyStoppingCallback
from scipy.stats import entropy
from sklearn.metr... | 6,161 | 31.603175 | 99 | py |
HeadlineCause | HeadlineCause-main/headline_cause/active_learning/infer_clf.py | import argparse
import json
import torch
import numpy as np
from scipy.stats import entropy
from scipy.special import softmax
from tqdm import tqdm
from transformers import AutoTokenizer, AutoModelForSequenceClassification
from util import write_jsonl, read_jsonl, gen_batch
def main(
input_path,
model_path,... | 2,774 | 32.035714 | 76 | py |
opioid-repurposing | opioid-repurposing-main/generate_bt_fps_mean.py | from fairseq.models.roberta import RobertaModel
import argparse
import sys
import numpy as np
import torch
def load_pretrain_model(model_name_or_path, checkpoint_file, data_name_or_path, bpe='smi'):
'''Currently only load to cpu()'''
# load model
pretrain_model = RobertaModel.from_pretrained(
mod... | 3,724 | 33.490741 | 91 | py |
LAMOL | LAMOL-master/test.py | import torch
import csv
import os
import json
import logging
from fp16 import FP16_Module
import GPUtil
from collections import OrderedDict
from settings import args, MODEL_CLASS, TOKENIZER, SPECIAL_TOKEN_IDS, init_logging
from settings import MEMORY_FACTOR, LEN_FACTOR, TASK_DICT, MODEL_CONFIG, DATA_ATTRS, SPECIAL_TOKE... | 6,865 | 41.645963 | 146 | py |
LAMOL | LAMOL-master/settings.py | import os
import json
import argparse
import logging
import datetime
logger = logging.getLogger(__name__)
import GPUtil
from pytorch_transformers import OpenAIGPTLMHeadModel, OpenAIGPTTokenizer, OpenAIGPTConfig
from pytorch_transformers import GPT2LMHeadModel, GPT2Tokenizer, GPT2Config, CONFIG_NAME
import torch
BAS... | 13,903 | 47.957746 | 133 | py |
LAMOL | LAMOL-master/utils.py | import torch
from torch.utils.data import Dataset, DataLoader, Sampler
import torch.nn.functional as F
import re
import csv
import json
import uuid
import pickle as pkl
import numpy as np
from copy import deepcopy
import os
from glob import glob
import logging
import pathlib
from collections import OrderedDict
from set... | 33,442 | 38.577515 | 150 | py |
LAMOL | LAMOL-master/scheduler.py | # coding=utf-8
# Copyright (c) 2019, 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 copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless re... | 2,930 | 38.608108 | 122 | py |
LAMOL | LAMOL-master/fp16util.py | # coding=utf-8
# Copyright (c) 2019, 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 copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless re... | 7,680 | 36.468293 | 337 | py |
LAMOL | LAMOL-master/regularizers.py | import abc
import math
import torch
from torch.optim import Optimizer, SGD
from settings import args, FILL_VAL, TOKENS_WEIGHT
from utils import get_losses, get_model_dir
from parallel import DataParallelCriterion
from torch.nn import CrossEntropyLoss, MSELoss
import pickle as pkl
import os
from torch.nn.functional impo... | 17,354 | 39.549065 | 137 | py |
LAMOL | LAMOL-master/loss_scaler.py | # coding=utf-8
# Copyright (c) 2019, 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 copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless re... | 9,788 | 40.130252 | 326 | py |
LAMOL | LAMOL-master/train.py | import torch
from torch.utils.data import DataLoader
from torch import nn
from pytorch_transformers import AdamW, WEIGHTS_NAME, WarmupLinearSchedule
import csv
import numpy as np
import os
import logging
from fp16 import FP16_Module, FP16_Optimizer
from parallel import DataParallelModel, DataParallelCriterion
from coll... | 10,296 | 48.267943 | 166 | py |
LAMOL | LAMOL-master/parallel.py | import threading
import torch
from torch.nn.parallel import DataParallel
from torch.nn.parallel.parallel_apply import get_a_var
from torch.nn.parallel.scatter_gather import scatter
torch_ver = torch.__version__[:3]
__all__ = ['DataParallelModel', 'DataParallelCriterion']
class DataParallelModel(DataParallel):
d... | 4,814 | 36.038462 | 91 | py |
LAMOL | LAMOL-master/fp16.py | # coding=utf-8
# Copyright (c) 2019, 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 copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless re... | 31,831 | 49.28752 | 437 | py |
capacity-approaching-autoencoders | capacity-approaching-autoencoders-master/gammaDIME.py | from keras import backend as K
# gamma-DIME loss
def gamma_dime_loss(args):
# define the parameter gamma
gamma = 1
t_xy = args[0]
t_xy_bar = args[1]
loss = -(gamma*K.mean(K.log(t_xy)) - K.mean(K.pow(t_xy_bar, gamma))+1)
return loss | 256 | 24.7 | 74 | py |
capacity-approaching-autoencoders | capacity-approaching-autoencoders-master/Capacity-Approaching_AE.py | from __future__ import absolute_import, division, print_function, unicode_literals
from keras.layers import Input, Dense, GaussianNoise, Concatenate, Lambda, Reshape, Flatten, Dropout
from keras.layers import BatchNormalization, Activation, ZeroPadding2D
from keras.models import Sequential, Model, load_model
from kera... | 15,913 | 37.626214 | 132 | py |
capacity-approaching-autoencoders | capacity-approaching-autoencoders-master/uniform_noise.py | from keras.engine import Layer
from keras import backend as K
class UniformNoise(Layer):
"""Apply additive uniform noise
Only active at training time since it is a regularization layer.
# Arguments
minval: Minimum value of the uniform distribution
maxval: Maximum value of the uniform dist... | 1,190 | 30.342105 | 69 | py |
vermouth-martinize | vermouth-martinize-master/doc/source/conf.py | # -*- coding: utf-8 -*-
#
# Configuration file for the Sphinx documentation builder.
#
# This file does only contain a selection of the most common options. For a
# full list see the documentation:
# http://www.sphinx-doc.org/en/stable/config
# -- Path setup ------------------------------------------------------------... | 8,080 | 32.953782 | 139 | py |
Memristive-Seizure-Detection-and-Prediction-by-Parallel-Convolutional-Neural-Networks | Memristive-Seizure-Detection-and-Prediction-by-Parallel-Convolutional-Neural-Networks-master/network_training/SWEC_ETHZ.py | import os
import numpy as np
import torch
from torch import nn
from torch.utils.data import DataLoader, Dataset
from torchvision import datasets, transforms
from torchsummary import summary
import torch.nn.functional as F
from sklearn.model_selection import KFold
from sklearn import preprocessing
import matplotlib.pypl... | 8,593 | 41.756219 | 202 | py |
Memristive-Seizure-Detection-and-Prediction-by-Parallel-Convolutional-Neural-Networks | Memristive-Seizure-Detection-and-Prediction-by-Parallel-Convolutional-Neural-Networks-master/network_training/utils.py | import torch
import numpy as np
def foldretrieve(fold,foldsData,foldsLabel):
testData = foldsData[fold]
testLabel = foldsLabel[fold]
allData = foldsData[0:fold]+foldsData[fold:-1]
allLabel = foldsLabel[0:fold]+foldsLabel[fold:-1]
try:
trainData = np.concatenate([*allData])
except:
... | 743 | 26.555556 | 53 | py |
Memristive-Seizure-Detection-and-Prediction-by-Parallel-Convolutional-Neural-Networks | Memristive-Seizure-Detection-and-Prediction-by-Parallel-Convolutional-Neural-Networks-master/network_training/Network.py | import torch
from torch import nn
import torch.nn.functional as F
import brevitas.nn as qnn
### Network Definition
class ParallelConvolution(nn.Module):
def __init__(self, size=32):
super(ParallelConvolution, self).__init__()
self.conv1 = qnn.QuantConv1d(1,32,size,weight_bit_width=6)
self.... | 954 | 33.107143 | 79 | py |
Memristive-Seizure-Detection-and-Prediction-by-Parallel-Convolutional-Neural-Networks | Memristive-Seizure-Detection-and-Prediction-by-Parallel-Convolutional-Neural-Networks-master/network_training/CHBMIT.py | import os
import numpy as np
import torch
from torch import nn
from torch.utils.data import DataLoader, Dataset
from torchvision import datasets, transforms
from torchsummary import summary
import torch.nn.functional as F
from sklearn.model_selection import KFold
from sklearn import preprocessing
import matplotlib.pypl... | 8,597 | 41.776119 | 188 | py |
Memristive-Seizure-Detection-and-Prediction-by-Parallel-Convolutional-Neural-Networks | Memristive-Seizure-Detection-and-Prediction-by-Parallel-Convolutional-Neural-Networks-master/network_training/Transfer_CHBMIT_SWEC_ETHZ.py | import os
import numpy as np
import torch
from torch import nn
from torch.utils.data import DataLoader, Dataset
from torchvision import datasets, transforms
from torchsummary import summary
import torch.nn.functional as F
from sklearn.model_selection import KFold
from sklearn import preprocessing
import matplotlib.pypl... | 12,878 | 48.918605 | 282 | py |
3DSC | 3DSC-main/superconductors_3D/machine_learning/Apply_ML_Models_v1_3.py | import warnings
# warnings.filterwarnings("ignore")
from sklearn.exceptions import ConvergenceWarning
warnings.simplefilter("ignore", category=ConvergenceWarning)
import os
warnings.simplefilter("ignore", category=FutureWarning)
import sys
import numpy as np
from matplotlib import pyplot as plt
import seaborn as sns
im... | 45,766 | 46.328852 | 303 | py |
3DSC | 3DSC-main/superconductors_3D/machine_learning/RGM_own.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Created on Tue Apr 20 17:24:04 2021
@author: timo
This script contains my wrapper of the RGM of 2020 Jin to go with the standard sklearn API.
"""
import os
import numpy as np
from superconductors_3D.machine_learning.Algorithms.RGM_Jin import RGM as RGM_Jin
import torc... | 26,342 | 45.054196 | 617 | py |
3DSC | 3DSC-main/superconductors_3D/machine_learning/Custom_Machine_Learning_v1_3.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Created on Fri Sep 11 10:14:31 2020
@author: timo
This module is for the class MachineLearning that automatically executes a lot of different models and prints and saves all the output.
"""
import warnings
# warnings.filterwarnings("ignore")
import os
# os.environ['TF... | 61,052 | 46.697656 | 418 | py |
3DSC | 3DSC-main/superconductors_3D/machine_learning/Algorithms/RGM_Jin_original.py | import torch
import torch.nn as nn
import torch.nn.functional as F
import math
import numpy as np
import random
class GradientReversal(torch.autograd.Function):
beta = 1.
@staticmethod
def forward(self, x):
return x.view_as(x)
@staticmethod
def backward(self, grad_output):
return ... | 4,194 | 37.842593 | 167 | py |
3DSC | 3DSC-main/superconductors_3D/machine_learning/Algorithms/RGM_Jin_210519_with_train_seperately_and_all_train_separately.py | import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.jit import TracerWarning
import math
import numpy as np
import random
from copy import deepcopy
import warnings
class GradientReversal(torch.autograd.Function):
beta = 1.
@staticmethod
def forward(self, x):
return x.vie... | 9,738 | 44.723005 | 145 | py |
3DSC | 3DSC-main/superconductors_3D/machine_learning/Algorithms/RGM_Jin.py | import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.jit import TracerWarning
import math
import numpy as np
import random
from copy import deepcopy
import warnings
from itertools import combinations
class GradientReversal(torch.autograd.Function):
beta = 1.
@staticmethod
def for... | 8,734 | 44.494792 | 164 | py |
3DSC | 3DSC-main/superconductors_3D/machine_learning/Algorithms/RGM_Jin_210424_only_one_class.py | import torch
import torch.nn as nn
import torch.nn.functional as F
import math
import numpy as np
import random
class GradientReversal(torch.autograd.Function):
beta = 1.
@staticmethod
def forward(self, x):
return x.view_as(x)
@staticmethod
def backward(self, grad_output):
return ... | 5,006 | 40.040984 | 122 | py |
3DSC | 3DSC-main/superconductors_3D/machine_learning/Algorithms/RGM_Jin_210515_old_train_seperetely.py | import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.jit import TracerWarning
import math
import numpy as np
import random
from copy import deepcopy
import warnings
class GradientReversal(torch.autograd.Function):
beta = 1.
@staticmethod
def forward(self, x):
return x.vie... | 7,049 | 43.620253 | 145 | py |
3DSC | 3DSC-main/superconductors_3D/machine_learning/own_libraries/models/GPflow_GP.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Created on Sun Oct 3 21:13:25 2021
@author: Timo Sommer
This script contains an implementation of a Gaussian Process that works with the GPflow models.
"""
import torch
from sklearn.base import RegressorMixin, BaseEstimator
import tensorflow as tf
import tensorflow_p... | 14,397 | 39.787535 | 281 | py |
3DSC | 3DSC-main/superconductors_3D/machine_learning/own_libraries/models/NN/MLP_Lightning.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Created on Thu Nov 4 10:36:50 2021
@author: Timo Sommer
This script includes a standard Neural Network based on pytorch lightning.
"""
import torch
from torch.nn import functional as F
from torch import nn
from torch.utils.data import DataLoader
from pytorch_lightnin... | 11,648 | 30.569106 | 136 | py |
3DSC | 3DSC-main/superconductors_3D/machine_learning/own_libraries/models/GNN/MEGNet_tf.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Created on Tue Sep 14 09:12:44 2021
@author: Timo Sommer
This script contains an implementation of MEGNet from the original authors based on tensorflow with an sklearn API.
"""
from sklearn.base import BaseEstimator, RegressorMixin
from megnet.models import MEGNetMode... | 21,677 | 40.688462 | 352 | py |
3DSC | 3DSC-main/superconductors_3D/machine_learning/own_libraries/analysis/Experiments/Run.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Created on Wed Aug 18 14:23:49 2021
@author: Timo Sommer
This script contains a class to plot stuff for ML runs.
"""
import os
import pandas as pd
from pandas.api.types import is_string_dtype
from pandas.api.types import is_numeric_dtype
import numpy as np
import mat... | 55,547 | 43.688656 | 274 | py |
3DSC | 3DSC-main/superconductors_3D/machine_learning/own_libraries/utils/Refactoring.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Created on Wed Sep 22 10:59:22 2021
@author: Timo Sommer
This script contains a class for checking if the output of the Machine_Learning() class is the same as in one reference directory. It is particular useful for automatically checking if the code still does the sa... | 9,634 | 42.795455 | 232 | py |
3DSC | 3DSC-main/superconductors_3D/machine_learning/own_libraries/utils/Models.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Created on Mon Nov 22 14:12:31 2021
@author: Timo Sommer
This script is a collection of classes for saving and loading models of the ML script.
"""
from megnet.models import MEGNetModel
import os
import pickle
import io
def get_modelpath(outdir, modelname, repetition... | 5,903 | 35.670807 | 182 | py |
MatchZoo | MatchZoo-master/setup.py | import io
import os
from setuptools import setup, find_packages
here = os.path.abspath(os.path.dirname(__file__))
# Avoids IDE errors, but actual version is read from version.py
__version__ = None
exec(open('matchzoo/version.py').read())
short_description = 'Facilitating the design, comparison and sharing of deep ... | 1,799 | 26.692308 | 99 | py |
MatchZoo | MatchZoo-master/matchzoo/__init__.py | from pathlib import Path
USER_DIR = Path.expanduser(Path('~')).joinpath('.matchzoo')
if not USER_DIR.exists():
USER_DIR.mkdir()
USER_DATA_DIR = USER_DIR.joinpath('datasets')
if not USER_DATA_DIR.exists():
USER_DATA_DIR.mkdir()
USER_TUNED_MODELS_DIR = USER_DIR.joinpath('tuned_models')
from .version import __ve... | 1,785 | 30.333333 | 78 | py |
MatchZoo | MatchZoo-master/matchzoo/models/cdssm.py | """An implementation of CDSSM (CLSM) model."""
import typing
import keras
from keras.models import Model
from matchzoo.engine.base_model import BaseModel
from matchzoo.engine.param import Param
from matchzoo.engine.param_table import ParamTable
from matchzoo import preprocessors
from matchzoo.utils import TensorType
... | 5,450 | 39.984962 | 78 | py |
MatchZoo | MatchZoo-master/matchzoo/models/drmm.py | """An implementation of DRMM Model."""
import typing
import keras
import keras.backend as K
import tensorflow as tf
from matchzoo.engine.base_model import BaseModel
from matchzoo.engine.param import Param
from matchzoo.engine.param_table import ParamTable
class DRMM(BaseModel):
"""
DRMM Model.
Examples... | 4,248 | 33.827869 | 78 | py |
MatchZoo | MatchZoo-master/matchzoo/models/duet.py | """DUET Model."""
import keras
import tensorflow as tf
from matchzoo.engine import hyper_spaces
from matchzoo.engine.base_model import BaseModel
from matchzoo.engine.param import Param
class DUET(BaseModel):
"""
DUET Model.
Examples:
>>> model = DUET()
>>> model.params['embedding_input_... | 6,502 | 39.141975 | 79 | py |
MatchZoo | MatchZoo-master/matchzoo/models/conv_knrm.py | """ConvKNRM model."""
import keras
import tensorflow as tf
from .knrm import KNRM
from matchzoo.engine.param import Param
class ConvKNRM(KNRM):
"""
ConvKNRM model.
Examples:
>>> model = ConvKNRM()
>>> model.params['embedding_input_dim'] = 10000
>>> model.params['embedding_output... | 3,736 | 37.132653 | 79 | py |
MatchZoo | MatchZoo-master/matchzoo/models/dssm.py | """An implementation of DSSM, Deep Structured Semantic Model."""
from keras.models import Model
from keras.layers import Input, Dot
from matchzoo.engine.param_table import ParamTable
from matchzoo.engine.base_model import BaseModel
from matchzoo import preprocessors
class DSSM(BaseModel):
"""
Deep structured... | 1,847 | 31.421053 | 77 | py |
MatchZoo | MatchZoo-master/matchzoo/models/match_pyramid.py | """An implementation of MatchPyramid Model."""
import typing
import keras
import matchzoo
from matchzoo.engine.base_model import BaseModel
from matchzoo.engine.param import Param
from matchzoo.engine.param_table import ParamTable
from matchzoo.engine import hyper_spaces
class MatchPyramid(BaseModel):
"""
Ma... | 4,014 | 34.530973 | 79 | py |
MatchZoo | MatchZoo-master/matchzoo/models/arci.py | """An implementation of ArcI Model."""
import typing
import keras
from matchzoo.engine.base_model import BaseModel
from matchzoo.engine.param import Param
from matchzoo.engine.param_table import ParamTable
from matchzoo.engine import hyper_spaces
class ArcI(BaseModel):
"""
ArcI Model.
Examples:
... | 5,386 | 37.205674 | 78 | py |
MatchZoo | MatchZoo-master/matchzoo/models/mvlstm.py | """An implementation of MVLSTM Model."""
import keras
import tensorflow as tf
from matchzoo.engine import hyper_spaces
from matchzoo.engine.base_model import BaseModel
from matchzoo.engine.param import Param
from matchzoo.engine.param_table import ParamTable
class MVLSTM(BaseModel):
"""
MVLSTM Model.
E... | 2,963 | 34.285714 | 77 | py |
MatchZoo | MatchZoo-master/matchzoo/models/anmm.py | """An implementation of aNMM Model."""
import keras
from keras.activations import softmax
from keras.initializers import RandomUniform
from matchzoo.engine.base_model import BaseModel
from matchzoo.engine.param import Param
from matchzoo.engine.param_table import ParamTable
from matchzoo.engine import hyper_spaces
... | 2,720 | 33.0125 | 75 | py |
MatchZoo | MatchZoo-master/matchzoo/models/drmmtks.py | """An implementation of DRMMTKS Model."""
import typing
import keras
import tensorflow as tf
from matchzoo.engine.base_model import BaseModel
from matchzoo.engine.param import Param
from matchzoo.engine.param_table import ParamTable
from matchzoo.engine import hyper_spaces
class DRMMTKS(BaseModel):
"""
DRMM... | 4,766 | 34.311111 | 79 | py |
MatchZoo | MatchZoo-master/matchzoo/models/arcii.py | """An implementation of ArcII Model."""
import typing
import keras
import matchzoo
from matchzoo.engine.base_model import BaseModel
from matchzoo.engine.param import Param
from matchzoo.engine.param_table import ParamTable
from matchzoo.engine import hyper_spaces
class ArcII(BaseModel):
"""
ArcII Model.
... | 4,891 | 36.630769 | 79 | py |
MatchZoo | MatchZoo-master/matchzoo/models/knrm.py | """KNRM model."""
import keras
import tensorflow as tf
from matchzoo.engine.base_model import BaseModel
from matchzoo.engine.param import Param
from matchzoo.engine import hyper_spaces
class KNRM(BaseModel):
"""
KNRM model.
Examples:
>>> model = KNRM()
>>> model.params['embedding_input_d... | 3,057 | 31.189474 | 78 | py |
MatchZoo | MatchZoo-master/matchzoo/models/naive.py | """Naive model with a simplest structure for testing purposes."""
import keras
from matchzoo.engine.base_model import BaseModel
from matchzoo.engine import hyper_spaces
class Naive(BaseModel):
"""
Naive model with a simplest structure for testing purposes.
Bare minimum functioning model. The best choic... | 909 | 28.354839 | 74 | py |
MatchZoo | MatchZoo-master/matchzoo/models/dense_baseline.py | """A simple densely connected baseline model."""
import keras.layers
from matchzoo.engine.base_model import BaseModel
from matchzoo.engine.param_table import ParamTable
from matchzoo.engine import hyper_spaces
class DenseBaseline(BaseModel):
"""
A simple densely connected baseline model.
Examples:
... | 1,420 | 31.295455 | 77 | py |
MatchZoo | MatchZoo-master/matchzoo/datasets/snli/load_data.py | """SNLI data loader."""
import typing
from pathlib import Path
import pandas as pd
import keras
import matchzoo
_url = "https://nlp.stanford.edu/projects/snli/snli_1.0.zip"
def load_data(
stage: str = 'train',
task: str = 'classification',
target_label: str = 'entailment',
return_classes: bool = F... | 3,067 | 33.863636 | 79 | py |
MatchZoo | MatchZoo-master/matchzoo/datasets/quora_qp/load_data.py | """Quora Question Pairs data loader."""
import typing
from pathlib import Path
import keras
import pandas as pd
import matchzoo
_url = "https://firebasestorage.googleapis.com/v0/b/mtl-sentence" \
"-representations.appspot.com/o/data%2FQQP.zip?alt=media&" \
"token=700c6acf-160d-4d89-81d1-de4191d02cb5"
... | 2,677 | 30.505882 | 74 | py |
MatchZoo | MatchZoo-master/matchzoo/datasets/cqa_ql_16/load_data.py | """CQA-QL-16 data loader."""
import xml
import typing
from pathlib import Path
import keras
import pandas as pd
import matchzoo
_train_dev_url = "http://alt.qcri.org/semeval2016/task3/data/uploads/" \
"semeval2016-task3-cqa-ql-traindev-v3.2.zip"
_test_url = "http://alt.qcri.org/semeval2016/task3/d... | 7,865 | 37.558824 | 79 | py |
MatchZoo | MatchZoo-master/matchzoo/datasets/embeddings/load_glove_embedding.py | """Embedding data loader."""
from pathlib import Path
import keras
import matchzoo as mz
_glove_embedding_url = "http://nlp.stanford.edu/data/glove.6B.zip"
def load_glove_embedding(dimension: int = 50) -> mz.embedding.Embedding:
"""
Return the pretrained glove embedding.
:param dimension: the size of... | 995 | 33.344828 | 78 | py |
MatchZoo | MatchZoo-master/matchzoo/datasets/wiki_qa/load_data.py | """WikiQA data loader."""
import typing
import csv
from pathlib import Path
import keras
import pandas as pd
import matchzoo
_url = "https://download.microsoft.com/download/E/5/F/" \
"E5FCFCEE-7005-4814-853D-DAA7C66507E0/WikiQACorpus.zip"
def load_data(
stage: str = 'train',
task: str = 'ranking',
... | 3,045 | 32.472527 | 79 | py |
MatchZoo | MatchZoo-master/matchzoo/layers/matching_layer.py | """An implementation of Matching Layer."""
import typing
import tensorflow as tf
from keras.engine import Layer
class MatchingLayer(Layer):
"""
Layer that computes a matching matrix between samples in two tensors.
:param normalize: Whether to L2-normalize samples along the
dot product axis befor... | 5,753 | 39.808511 | 78 | py |
MatchZoo | MatchZoo-master/matchzoo/layers/dynamic_pooling_layer.py | """An implementation of Dynamic Pooling Layer."""
import typing
import tensorflow as tf
from keras.engine import Layer
class DynamicPoolingLayer(Layer):
"""
Layer that computes dynamic pooling of one tensor.
:param psize1: pooling size of dimension 1
:param psize2: pooling size of dimension 2
:p... | 4,315 | 32.457364 | 78 | py |
MatchZoo | MatchZoo-master/matchzoo/data_generator/data_generator.py | """Base generator."""
import math
import typing
import keras
import numpy as np
import pandas as pd
import matchzoo as mz
from matchzoo.data_generator.callbacks import Callback
class DataGenerator(keras.utils.Sequence):
"""
Data Generator.
Used to divide a :class:`matchzoo.DataPack` into batches. This... | 9,187 | 30.251701 | 78 | py |
MatchZoo | MatchZoo-master/matchzoo/engine/base_model.py | """Base Model."""
import abc
import typing
from pathlib import Path
import dill
import numpy as np
import keras
import keras.backend as K
import pandas as pd
import matchzoo
from matchzoo import DataGenerator
from matchzoo.engine import hyper_spaces
from matchzoo.engine.base_preprocessor import BasePreprocessor
from... | 20,711 | 34.587629 | 79 | py |
MatchZoo | MatchZoo-master/matchzoo/engine/callbacks.py | """Callbacks."""
import typing
from pathlib import Path
import numpy as np
import keras
import matchzoo
from matchzoo.engine.base_model import BaseModel
class EvaluateAllMetrics(keras.callbacks.Callback):
"""
Callback to evaluate all metrics.
MatchZoo metrics can not be evaluated batch-wise since they ... | 2,513 | 32.972973 | 79 | py |
MatchZoo | MatchZoo-master/matchzoo/engine/parse_metric.py | import typing
import matchzoo
from matchzoo.engine.base_metric import BaseMetric
from matchzoo.engine import base_task
def parse_metric(
metric: typing.Union[str, typing.Type[BaseMetric], BaseMetric],
task: 'base_task.BaseTask' = None
) -> typing.Union['BaseMetric', str]:
"""
Parse input metric in an... | 2,559 | 31.405063 | 78 | py |
MatchZoo | MatchZoo-master/matchzoo/utils/make_keras_optimizer_picklable.py | import keras
def make_keras_optimizer_picklable():
"""
Fix https://github.com/NTMC-Community/MatchZoo/issues/726.
This function changes how keras behaves, use with caution.
"""
def __getstate__(self):
return keras.optimizers.serialize(self)
def __setstate__(self, state):
opti... | 517 | 24.9 | 62 | py |
MatchZoo | MatchZoo-master/matchzoo/utils/__init__.py | from .one_hot import one_hot
from .tensor_type import TensorType
from .list_recursive_subclasses import list_recursive_concrete_subclasses
from .make_keras_optimizer_picklable import make_keras_optimizer_picklable
| 214 | 42 | 74 | py |
MatchZoo | MatchZoo-master/matchzoo/contrib/models/esim.py | """ESIM model."""
import keras
import keras.backend as K
import tensorflow as tf
import matchzoo as mz
from matchzoo.engine.base_model import BaseModel
from matchzoo.engine.param import Param
from matchzoo.engine.param_table import ParamTable
class ESIM(BaseModel):
"""
ESIM model.
Examples:
>>>... | 7,807 | 35.657277 | 90 | py |
MatchZoo | MatchZoo-master/matchzoo/contrib/models/match_lstm.py | """Match LSTM model."""
import keras
import keras.backend as K
import tensorflow as tf
from matchzoo.engine.base_model import BaseModel
from matchzoo.engine.param import Param
from matchzoo.engine import hyper_spaces
class MatchLSTM(BaseModel):
"""
Match LSTM model.
Examples:
>>> model = MatchLS... | 4,182 | 39.221154 | 81 | py |
MatchZoo | MatchZoo-master/matchzoo/contrib/models/hbmp.py | """HBMP model."""
import keras
import typing
from matchzoo.engine import hyper_spaces
from matchzoo.engine.param_table import ParamTable
from matchzoo.engine.param import Param
from matchzoo.engine.base_model import BaseModel
class HBMP(BaseModel):
"""
HBMP model.
Examples:
>>> model = HBMP()
... | 5,896 | 37.045161 | 79 | py |
MatchZoo | MatchZoo-master/matchzoo/contrib/models/diin.py | """DIIN model."""
import typing
import keras
import keras.backend as K
import tensorflow as tf
from matchzoo import preprocessors
from matchzoo.contrib.layers import DecayingDropoutLayer
from matchzoo.contrib.layers import EncodingLayer
from matchzoo.engine import hyper_spaces
from matchzoo.engine.base_model import B... | 12,960 | 40.27707 | 78 | py |
MatchZoo | MatchZoo-master/matchzoo/contrib/models/match_srnn.py | """An implementation of Match-SRNN Model."""
import keras
from matchzoo.contrib.layers import MatchingTensorLayer
from matchzoo.contrib.layers import SpatialGRU
from matchzoo.engine import hyper_spaces
from matchzoo.engine.base_model import BaseModel
from matchzoo.engine.param import Param
from matchzoo.engine.param_... | 3,058 | 31.542553 | 76 | py |
MatchZoo | MatchZoo-master/matchzoo/contrib/models/bimpm.py | """BiMPM."""
from keras.models import Model
from keras.layers import Dense, Concatenate, Dropout
from keras.layers import Bidirectional, LSTM
from matchzoo.engine.param import Param
from matchzoo.engine.param_table import ParamTable
from matchzoo.engine.base_model import BaseModel
from matchzoo.contrib.layers import ... | 6,010 | 39.073333 | 98 | py |
MatchZoo | MatchZoo-master/matchzoo/contrib/layers/decaying_dropout_layer.py | """An implementation of Decaying Dropout Layer."""
import tensorflow as tf
from keras import backend as K
from keras.engine import Layer
class DecayingDropoutLayer(Layer):
"""
Layer that processes dropout with exponential decayed keep rate during
training.
:param initial_keep_rate: the initial keep r... | 3,805 | 37.06 | 75 | py |
MatchZoo | MatchZoo-master/matchzoo/contrib/layers/spatial_gru.py | """An implementation of Spatial GRU Layer."""
import typing
import tensorflow as tf
from keras import backend as K
from keras.engine import Layer
from keras.layers import Permute
from keras.layers import Reshape
from keras import activations
from keras import initializers
class SpatialGRU(Layer):
"""
Spatial ... | 10,175 | 33.969072 | 77 | py |
MatchZoo | MatchZoo-master/matchzoo/contrib/layers/attention_layer.py | """An implementation of Attention Layer for Bimpm model."""
import tensorflow as tf
from keras import backend as K
from keras.engine import Layer
class AttentionLayer(Layer):
"""
Layer that compute attention for BiMPM model.
For detailed information, see Bilateral Multi-Perspective Matching for
Natu... | 4,960 | 33.213793 | 83 | py |
MatchZoo | MatchZoo-master/matchzoo/contrib/layers/semantic_composite_layer.py | """An implementation of EncodingModule for DIIN model."""
import tensorflow as tf
from keras import backend as K
from keras.engine import Layer
from matchzoo.contrib.layers import DecayingDropoutLayer
class EncodingLayer(Layer):
"""
Apply a self-attention layer and a semantic composite fuse gate
to comp... | 4,198 | 33.418033 | 75 | py |
MatchZoo | MatchZoo-master/matchzoo/contrib/layers/multi_perspective_layer.py | """An implementation of MultiPerspectiveLayer for Bimpm model."""
import tensorflow as tf
from keras import backend as K
from keras.engine import Layer
from matchzoo.contrib.layers.attention_layer import AttentionLayer
class MultiPerspectiveLayer(Layer):
"""
A keras implementation of multi-perspective layer... | 16,251 | 33.652452 | 80 | py |
MatchZoo | MatchZoo-master/matchzoo/contrib/layers/matching_tensor_layer.py | """An implementation of Matching Tensor Layer."""
import typing
import numpy as np
import tensorflow as tf
from keras import backend as K
from keras.engine import Layer
from keras.initializers import constant
class MatchingTensorLayer(Layer):
"""
Layer that captures the basic interactions between two tensors... | 5,169 | 37.014706 | 78 | py |
MatchZoo | MatchZoo-master/matchzoo/losses/rank_hinge_loss.py | """The rank hinge loss."""
import numpy as np
import tensorflow as tf
from keras import layers, backend as K
from keras.losses import Loss
from keras.utils import losses_utils
class RankHingeLoss(Loss):
"""
Rank hinge loss.
Examples:
>>> from keras import backend as K
>>> x_pred = K.vari... | 2,253 | 30.305556 | 79 | py |
MatchZoo | MatchZoo-master/matchzoo/losses/rank_cross_entropy_loss.py | """The rank cross entropy loss."""
import numpy as np
import tensorflow as tf
from keras import layers, backend as K
from keras.losses import Loss
from keras.utils import losses_utils
class RankCrossEntropyLoss(Loss):
"""
Rank cross entropy loss.
Examples:
>>> from keras import backend as K
... | 2,389 | 35.212121 | 78 | py |
MatchZoo | MatchZoo-master/tests/unit_test/test_layers.py | import numpy as np
import pytest
from keras import backend as K
from matchzoo import layers
from matchzoo.contrib.layers import SpatialGRU
from matchzoo.contrib.layers import MatchingTensorLayer
def test_matching_layers():
s1_value = np.array([[[1, 2], [2, 3], [3, 4]],
[[0.1, 0.2], [0.2,... | 2,369 | 37.852459 | 89 | py |
MatchZoo | MatchZoo-master/tests/unit_test/test_losses.py | import numpy as np
from keras import backend as K
from matchzoo import losses
def test_hinge_loss():
true_value = K.variable(np.array([[1.2], [1],
[1], [1]]))
pred_value = K.variable(np.array([[1.2], [0.1],
[0], [-0.3]]))
expecte... | 2,082 | 39.843137 | 73 | py |
MatchZoo | MatchZoo-master/tests/unit_test/test_data_generator.py | import copy
import pytest
import keras
import matchzoo as mz
@pytest.fixture(scope='module')
def data_gen():
return mz.DataGenerator(mz.datasets.toy.load_data())
@pytest.mark.parametrize('attr', [
'callbacks',
'num_neg',
'num_dup',
'mode',
'batch_size',
'shuffle',
])
def test_data_gen... | 1,700 | 24.772727 | 71 | py |
MatchZoo | MatchZoo-master/tests/unit_test/models/test_models.py | """
These tests are simplied because the original verion takes too much time to
run, making CI fails as it reaches the time limit.
"""
import pytest
import copy
from pathlib import Path
import shutil
import matchzoo as mz
from keras.backend import clear_session
@pytest.fixture(scope='module', params=[
mz.tasks.R... | 2,603 | 22.889908 | 75 | py |
MatchZoo | MatchZoo-master/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,927 | 31.751381 | 79 | py |
Analyzing-the-Generalization-Capability-of-SGLD-Using-Properties-of-Gaussian-Channels | Analyzing-the-Generalization-Capability-of-SGLD-Using-Properties-of-Gaussian-Channels-main/code/main.py | import numpy as np
import torch
import math
from torch import nn, optim
from torch.utils.data import DataLoader
from torch.utils.data import SubsetRandomSampler
import importlib
import copy
import argparse
from torchvision import transforms, datasets
from torch.autograd import Variable
from torch.optim import Optimizer... | 14,060 | 39.059829 | 251 | py |
Analyzing-the-Generalization-Capability-of-SGLD-Using-Properties-of-Gaussian-Channels | Analyzing-the-Generalization-Capability-of-SGLD-Using-Properties-of-Gaussian-Channels-main/code/models/fc.py | import torch.nn as nn
class Network(nn.Module):
def __init__(self, nchannels, nclasses):
super(Network, self).__init__()
self.classifier = nn.Sequential(nn.Linear( nchannels * 32 * 32, 32, bias=True), nn.ReLU(inplace=True),
nn.Linear( 32, 32, bias=True), nn.R... | 525 | 36.571429 | 110 | py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.