repo stringlengths 2 99 | file stringlengths 13 225 | code stringlengths 0 18.3M | file_length int64 0 18.3M | avg_line_length float64 0 1.36M | max_line_length int64 0 4.26M | extension_type stringclasses 1
value |
|---|---|---|---|---|---|---|
marmot | marmot-master/marmot/representations/alignment_file_representation_generator.py | from __future__ import print_function
import numpy as np
import sys
from collections import defaultdict
from marmot.representations.representation_generator import RepresentationGenerator
class AlignmentFileRepresentationGenerator(RepresentationGenerator):
'''
Get alignments from file
'''
# parse lex... | 3,351 | 40.9 | 161 | py |
marmot | marmot-master/marmot/representations/word_qe_files_representation_generator.py | import codecs
import os
from marmot.representations.representation_generator import RepresentationGenerator
class WordQEFilesRepresentationGenerator(RepresentationGenerator):
'''
The standard word-level format: 3 files, source, target, tags, one line per file, whitespace tokenized
'''
def __init__(s... | 1,195 | 37.580645 | 173 | py |
marmot | marmot-master/marmot/representations/syntactic_representation_generator.py | from marmot.util.extract_syntactic_features import call_stanford, call_parzu, parse_xml, parse_conll
from marmot.representations.representation_generator import RepresentationGenerator
class SyntacticRepresentationGenerator(RepresentationGenerator):
def __init__(self, tmp_dir, reverse=False):
self.tmp_di... | 1,524 | 48.193548 | 100 | py |
marmot | marmot-master/marmot/representations/segmentation_simple_representation_generator.py | import codecs
import re
from marmot.representations.representation_generator import RepresentationGenerator
class SegmentationSimpleRepresentationGenerator(RepresentationGenerator):
'''
Source, target, tags, segmentation files, one line per file, whitespace tokenized
Segmentation file -- can be Moses out... | 5,693 | 50.763636 | 157 | py |
marmot | marmot-master/marmot/representations/representation_generator.py | # an abstract class representing a representation generator
# returns the data object
# { representation_name: representation}
# <representation_name> -- string
# <representation> -- list of lists, representation of the whole dataset
from abc import ABCMeta, abstractmethod
class RepresentationGenerator(object):
... | 520 | 26.421053 | 72 | py |
marmot | marmot-master/marmot/representations/__init__.py | 0 | 0 | 0 | py | |
marmot | marmot-master/marmot/representations/segmentation_double_representation_generator.py | from marmot.representations.representation_generator import RepresentationGenerator
import codecs
class SegmentationDoubleRepresentationGenerator(RepresentationGenerator):
'''
Both source and target are already segmented with '||'
'''
def get_segments_from_line(self, line):
seg = line.strip('... | 1,990 | 40.479167 | 193 | py |
marmot | marmot-master/marmot/representations/pos_representation_generator.py | from subprocess import Popen
import os
import time
from marmot.representations.representation_generator import RepresentationGenerator
from marmot.experiment.import_utils import mk_tmp_dir
class POSRepresentationGenerator(RepresentationGenerator):
def _get_random_name(self, suffix=''):
return 'tmp_'+suf... | 2,447 | 36.090909 | 123 | py |
marmot | marmot-master/marmot/representations/google_translate_representation_generator.py | from __future__ import print_function
from nltk import word_tokenize
from goslate import Goslate
from marmot.representations.representation_generator import RepresentationGenerator
class GoogleTranslateRepresentationGenerator(RepresentationGenerator):
'''
Generate pseudoreference with Google Translate
'... | 1,043 | 28.828571 | 109 | py |
marmot | marmot-master/marmot/representations/tests/test_segmentation_simple_representation_generator.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
import unittest
from marmot.representations.segmentation_simple_representation_generator import SegmentationSimpleRepresentationGenerator
class WordQERepresentationGeneratorTests(unittest.TestCase):
def test_generate(self):
gen_target = SegmentationSimpleReprese... | 2,517 | 58.952381 | 181 | py |
marmot | marmot-master/marmot/representations/tests/test_wmt_representation_generator.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
import unittest
import yaml
import os
import shutil
import marmot
from marmot.representations.wmt_representation_generator import WMTRepresentationGenerator
from marmot.experiment.import_utils import build_object
def join_with_module_path(loader, node):
""" define custom... | 2,988 | 39.391892 | 116 | py |
marmot | marmot-master/marmot/representations/tests/test_word_qe_representation_generator.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
import unittest
import os
import yaml
import marmot
from marmot.representations.word_qe_representation_generator import WordQERepresentationGenerator
from marmot.experiment.import_utils import build_object
def join_with_module_path(loader, node):
""" define custom tag h... | 2,265 | 37.40678 | 101 | py |
marmot | marmot-master/marmot/representations/tests/test_alignment_representation_generator.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
import unittest
from marmot.representations.word_qe_representation_generator import WordQERepresentationGenerator
from marmot.representations.alignment_representation_generator import AlignmentRepresentationGenerator
class WordQERepresentationGeneratorTests(unittest.TestCase... | 958 | 42.590909 | 225 | py |
marmot | marmot-master/marmot/representations/tests/__init__.py | 0 | 0 | 0 | py | |
marmot | marmot-master/marmot/representations/tests/test_word_qe_and_pseudo_ref_representation_generator.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
import unittest
import os
import yaml
import marmot
from marmot.representations.word_qe_and_pseudo_ref_representation_generator import WordQEAndPseudoRefRepresentationGenerator
from marmot.experiment.import_utils import build_object
def join_with_module_path(loader, node):
... | 2,488 | 40.483333 | 124 | py |
marmot | marmot-master/examples/word_level_quality_estimation/wmt_word_level_experiment.py | from argparse import ArgumentParser
import yaml
import os, sys
import logging
import numpy as np
import marmot
from marmot.experiment import learning_utils
import marmot.experiment.experiment_utils as experiment_utils
from marmot.evaluation.evaluation_metrics import weighted_fmeasure
logging.basicConfig(format='%(... | 6,898 | 48.633094 | 148 | py |
LayerAct | LayerAct-main/ResNet.py | from functools import partial
from typing import Any, Callable, List, Optional, Type, Union
import numpy as np
import random
import os
import torch
import torch.nn as nn
from torch import Tensor
def random_seed_set(rs) :
torch.manual_seed(rs)
torch.cuda.manual_seed(rs)
torch.cuda.manual_seed_all(rs)
... | 11,184 | 33.953125 | 149 | py |
LayerAct | LayerAct-main/test.py | import argparse
import os
import numpy as np
import pandas as pd
import random
import torch
import torch.nn as nn
import torch.nn.parallel
import torch.backends.cudnn as cudnn
import torch.optim
import torch.utils.data
from collections import OrderedDict as OD
from LayerAct import LA_HardSiLU, LA_SiLU
import data_aug... | 6,329 | 42.356164 | 149 | py |
LayerAct | LayerAct-main/train_validate.py | import time
from enum import Enum
import torch
import torch.nn.parallel
import torch.optim
import torch.utils.data
import shutil
def save_checkpoint(state, is_best, filename='checkpoint.pth.tar'):
torch.save(state, filename)
def accuracy(output, target, topk=(1,)):
"""Computes the accuracy over the k top pre... | 7,326 | 32.153846 | 101 | py |
LayerAct | LayerAct-main/train_parallel.py | import argparse
import time
import os
import sys
import numpy as np
import random
import shutil
import torch
import torch.nn as nn
import torch.nn.parallel
import torch.backends.cudnn as cudnn
import torch.optim
import torch.utils.data
from LayerAct import LA_HardSiLU, LA_SiLU
import data_augmentation
from train_val... | 8,871 | 42.920792 | 166 | py |
LayerAct | LayerAct-main/ResNet_small.py | import torch.nn as nn
import torch.nn.functional as F
class ResNet(nn.Module):
def __init__(self, activation, activation_params, rs, layers, num_classes):
super(ResNet, self).__init__()
self.conv1 = nn.Conv2d(3, 16, kernel_size=3, stride=1, padding=1)
self.norm1 = nn.BatchNorm2d(16)
... | 3,640 | 36.536082 | 101 | py |
LayerAct | LayerAct-main/LayerAct.py | # importing
import torch
import torch.nn as nn
import warnings
warnings.filterwarnings('ignore')
# function to calculate the layer-direction mean and variance.
def calculate_mean_std_for_forward(inputs, std = True) :
if len(inputs.shape) < 4 :
cal_dim = [1]
else :
cal_dim = [1, 2, 3]
... | 6,523 | 32.803109 | 125 | py |
LayerAct | LayerAct-main/data_augmentation.py | import os
import numpy as np
import torch.utils.data
import torchvision
import torchvision.transforms as transforms
from torch.utils.data.sampler import SubsetRandomSampler
from sklearn.model_selection import StratifiedShuffleSplit
import random
from ResNet import resnet18, resnet50, resnet101
from ResNet_small impor... | 9,943 | 39.422764 | 128 | py |
LayerAct | LayerAct-main/train.py | import argparse
import time
import os
import sys
import numpy as np
import random
import shutil
import torch
import torch.nn as nn
import torch.nn.parallel
import torch.backends.cudnn as cudnn
import torch.optim
import torch.utils.data
from LayerAct import LA_HardSiLU, LA_SiLU
import data_augmentation
from train_val... | 8,519 | 42.469388 | 165 | py |
EQL | EQL-master/EQL-DIV-ICML-Python3/createjobs-f1.py | #!/usr/bin/python
# sample perl script to create SGE jobs (sun grid engine)
# for scanning a parameter space
import os
jobname = "F1_" # should be short
name = "" + jobname # name of shell scripts
res = "result_f1-EQLDIV"
submitfile = "submit_" + name + ".sh"
SUBMIT = open(submitfile,'w')
SUBMIT.write("#/bin/bash\n... | 2,187 | 28.173333 | 92 | py |
EQL | EQL-master/EQL-DIV-ICML-Python3/__init__.py | 0 | 0 | 0 | py | |
EQL | EQL-master/EQL-DIV-ICML-Python3/src/graph_separate.py | from graphviz import Digraph
import numpy as np
def getEdges(matrix,inputnames,outputnames,thresh=0.1):
edges=[]
it = np.nditer(matrix, flags=['multi_index'])
while not it.finished:
if np.abs(it[0])>thresh:
edges.append((inputnames[it.multi_index[0]],outputnames[it.multi_index[1]],np.r... | 2,731 | 32.317073 | 113 | py |
EQL | EQL-master/EQL-DIV-ICML-Python3/src/mlp.py | """
Multilayer function graph for system identification
This will simply use regression in the square error with
L1 norm on weights to get a sparse representation
It follows the multilayer perceptron style, but has more complicated
nodes.
.. math:: Each layer is
y(x) = {f^{(1)}(W^{(1)} x), f^{(2)}(W^{(2)} x... | 22,132 | 31.500734 | 110 | py |
EQL | EQL-master/EQL-DIV-ICML-Python3/src/utils.py | """
Utility functions
"""
import csv
import numpy as np
import theano
from itertools import chain
import os
import gzip
import pickle
#import dill
__docformat__ = 'restructedtext en'
def softmax(x):
e_x = np.exp(x - np.max(x))
out = e_x / e_x.sum()
return out
def relative_prob(x):
e_x = (x - np.m... | 6,415 | 27.264317 | 106 | py |
EQL | EQL-master/EQL-DIV-ICML-Python3/src/graph.py | from graphviz import Digraph
import numpy as np
def getEdges(matrix,inputnames,outputnames,thresh=0.1):
edges=[]
it = np.nditer(matrix, flags=['multi_index'])
while not it.finished:
if np.abs(it[0])>thresh:
edges.append((inputnames[it.multi_index[0]],outputnames[it.multi_index[1]],np.r... | 2,731 | 32.317073 | 113 | py |
EQL | EQL-master/EQL-DIV-ICML-Python3/src/mlfg_final.py | """
Multilayer function graph for system identification.
This is able to learn typical algebraic expressions with
maximal multiplicative/application term length given by the number of layers.
TWe use regression with square error and
L1 norm on weights to get a sparse representations.
It follows the multilayer per... | 35,927 | 33.446788 | 223 | py |
EQL | EQL-master/EQL-DIV-ICML-Python3/src/noise.py | # Copyright (c) 2011 Leif Johnson <leif@leifjohnson.net>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify,... | 4,719 | 31.777778 | 80 | py |
EQL | EQL-master/EQL-DIV-ICML-Python3/src/model_selection_val_sparsity.py | import os, sys
import stat
import numpy as np
from operator import itemgetter
'''
expects a file with one row per network and columns reporting the parameters and sparsity and performance
First line should be the column names, #C col1 col2 col3...
then one additional comments line: # extrapolation datasets etc
A sampl... | 3,446 | 41.555556 | 138 | py |
EQL | EQL-master/EQL-DIV-ICML-Python3/src/graph_div.py | from graphviz import Digraph
import numpy as np
def getEdges(matrix,inputnames,outputnames,thresh=0.1):
edges=[]
it = np.nditer(matrix, flags=['multi_index'])
while not it.finished:
if np.abs(it[0])>thresh:
edges.append((inputnames[it.multi_index[0]],outputnames[it.multi_index[1]],np.r... | 2,998 | 34.702381 | 113 | py |
EQL | EQL-master/EQL-DIV-ICML-Python3/src/__init__.py | 0 | 0 | 0 | py | |
EQL | EQL-master/EQL-DIV-ICML-Python3/src/svr.py | """
SVR from sklearn
"""
import time
import sys
import timeit
import getopt
import numpy
import pickle
from sklearn.svm import SVR
from .utils import *
__docformat__ = 'restructedtext en'
def evaluate_svr(x,model):
predictions = []
for (d, svr) in model:
predictions.append(svr.predict(x))
return np.t... | 5,887 | 27.307692 | 111 | py |
EQL | EQL-master/EQL-DIV-ICML/createjobs.py | #!/usr/bin/python
# sample perl script to create SGE jobs (sun grid engine)
# for scanning a parameter space
import os
jobname = "F0_" # should be short
name = "" + jobname # name of shell scripts
res = "result_f0-EQLDIV"
submitfile = "submit_" + name + ".sh"
SUBMIT = open(submitfile,'w')
SUBMIT.write("#/bin/bash\n... | 2,184 | 28.133333 | 92 | py |
EQL | EQL-master/EQL-DIV-ICML/createjobs-f1.py | #!/usr/bin/python
# sample perl script to create SGE jobs (sun grid engine)
# for scanning a parameter space
import os
jobname = "F1_" # should be short
name = "" + jobname # name of shell scripts
res = "result_f1-EQLDIV"
submitfile = "submit_" + name + ".sh"
SUBMIT = open(submitfile,'w')
SUBMIT.write("#/bin/bash\n... | 2,186 | 28.16 | 92 | py |
EQL | EQL-master/EQL-DIV-ICML/__init__.py | 0 | 0 | 0 | py | |
EQL | EQL-master/EQL-DIV-ICML/result_f0-EQLDIV/createtasksIS-base.py | #!/usr/bin/python
# sample perl script to create SGE jobs (sun grid engine)
# for scanning a parameter space
import os
jobname = "FG1_" # should be short
name = "" + jobname # name of shell scripts
res = "result_fg1a-fg"
mem = "2000"
#maxtime = "4:00:00"
submitfile = "submit_" + name + ".sh"
SUBMIT = open(submitfi... | 3,626 | 32.897196 | 94 | py |
EQL | EQL-master/EQL-DIV-ICML/src/utils.py | """
Utility functions
"""
import csv
import numpy as np
import theano
from itertools import chain
import os
import gzip
import cPickle
__docformat__ = 'restructedtext en'
def softmax(x):
e_x = np.exp(x - np.max(x))
out = e_x / e_x.sum()
return out
def relative_prob(x):
e_x = (x - np.min(x))
o... | 6,220 | 27.277273 | 106 | py |
EQL | EQL-master/EQL-DIV-ICML/src/mlfg_final.py | """
Multilayer function graph for system identification.
This is able to learn typical algebraic expressions with
maximal multiplicative/application term length given by the number of layers.
We use regression with square error and
L1 norm on weights to get a sparse representations.
It follows the multilayer perc... | 35,587 | 33.384541 | 221 | py |
EQL | EQL-master/EQL-DIV-ICML/src/noise.py | # Copyright (c) 2011 Leif Johnson <leif@leifjohnson.net>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify,... | 4,693 | 31.825175 | 80 | py |
EQL | EQL-master/EQL-DIV-ICML/src/model_selection_val_sparsity.py | import os, sys
import stat
import numpy as np
from operator import itemgetter
'''
expects a file with one row per network and columns reporting the parameters and sparsity and performance
First line should be the column names, #C col1 col2 col3...
then one additional comments line: # extrapolation datasets etc
A sampl... | 3,431 | 41.37037 | 138 | py |
EQL | EQL-master/EQL-DIV-ICML/src/graph_div.py | from graphviz import Digraph
import numpy as np
def getEdges(matrix,inputnames,outputnames,thresh=0.1):
edges=[]
it = np.nditer(matrix, flags=['multi_index'])
while not it.finished:
if np.abs(it[0])>thresh:
edges.append((inputnames[it.multi_index[0]],outputnames[it.multi_index[1]],np.r... | 2,993 | 34.642857 | 113 | py |
EQL | EQL-master/EQL-DIV-ICML/src/__init__.py | 0 | 0 | 0 | py | |
EQL | EQL-master/EQL-DIV-ICML/result_f1-EQLDIV/createjobs.py | #!/usr/bin/python
# sample perl script to create SGE jobs (sun grid engine)
# for scanning a parameter space
import os
jobname = "F1_" # should be short
name = "" + jobname # name of shell scripts
res = "result_f1-EQLDIV"
mem = "2000"
#maxtime = "4:00:00"
submitfile = "submit_" + name + ".sh"
SUBMIT = open(submitf... | 2,191 | 27.467532 | 80 | py |
mkbe | mkbe-master/DesGAN/generate.py | import argparse
import numpy as np
import random
import torch
from torch.autograd import Variable
from models import load_models, generate
###############################################################################
# Generation methods
#############################################################################... | 5,149 | 36.867647 | 79 | py |
mkbe | mkbe-master/DesGAN/utils.py | import os
import torch
import numpy as np
import random
def load_kenlm():
global kenlm
import kenlm
def to_gpu(gpu, var):
if gpu:
return var.cuda()
return var
class Dictionary(object):
def __init__(self):
self.word2idx = {}
self.idx2word = {}
self.word2idx['<pad... | 8,267 | 30.557252 | 79 | py |
mkbe | mkbe-master/DesGAN/models.py | import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Variable
from torch.nn.utils.rnn import pack_padded_sequence, pad_packed_sequence
from utils import to_gpu
import json
import os
import numpy as np
class MLP_D(nn.Module):
def __init__(self, ninput, noutput, layers,
... | 12,561 | 33.991643 | 82 | py |
mkbe | mkbe-master/DesGAN/metrics.py | """
Computes the BLEU, ROUGE, METEOR, and CIDER
using the COCO metrics scripts
"""
import argparse
import logging
# this requires the coco-caption package, https://github.com/tylin/coco-caption
from pycocoevalcap.bleu.bleu import Bleu
from pycocoevalcap.rouge.rouge import Rouge
from pycocoevalcap.cider.cider import Ci... | 2,904 | 32.390805 | 121 | py |
mkbe | mkbe-master/DesGAN/train.py | import argparse
import os
import time
import math
import numpy as np
import random
import sys
import json
from sklearn import preprocessing
import torch
import torch.nn as nn
import torch.optim as optim
import torch.nn.functional as F
from torch.autograd import Variable
from utils import to_gpu, Corpus, batchify, tra... | 26,814 | 37.472023 | 100 | py |
mkbe | mkbe-master/MKBE/models/conv_units.py | """CNN building blocks derived from Inception-ResNet-v2
"""
import tensorflow as tf
def print_variable_info():
"""
auxiliary function to print trainable variable information
"""
var_list = tf.trainable_variables()
total = 0
layer_name = ""
layer_total = 0
for var in var_list:
... | 19,724 | 40.179541 | 120 | py |
mkbe | mkbe-master/MKBE/models/ml_distmult.py | # Relations used: age, gender, occupation, zip, title, release date, genre, rating(1-5)
import metrics
import tensorflow as tf
#from compact_bilinear_pooling import compact_bilinear_pooling_layer
def activation(x):
with tf.name_scope("selu") as scope:
alpha = 1.6732632423543772848170429916717
scal... | 28,863 | 50.359431 | 120 | py |
mkbe | mkbe-master/MKBE/models/yago_convE_kb.py | import tensorflow as tf
def activation(x):
"""
with tf.name_scope("selu") as scope:
alpha = 1.6732632423543772848170429916717
scale = 1.0507009873554804934193349852946
return scale * tf.where(x >= 0.0, x, alpha * tf.nn.elu(x))
"""
return tf.tanh(x)
def define_graph(hyperparam... | 18,131 | 44.672544 | 120 | py |
mkbe | mkbe-master/MKBE/models/__init__.py | #from .ml_ConvE import *
from .ml_distmult import * | 51 | 25 | 26 | py |
mkbe | mkbe-master/MKBE/models/ml_convE_kb.py | # Relations used: age, gender, occupation, zip, title, release date, genre, rating(1-5)
import tensorflow as tf
import metrics
def activation(x):
"""
with tf.name_scope("selu") as scope:
alpha = 1.6732632423543772848170429916717
scale = 1.0507009873554804934193349852946
return scale *... | 33,237 | 51.842607 | 120 | py |
mkbe | mkbe-master/MKBE/models/yago_convE_kb_model.py | import tensorflow as tf
from tensorpack import *
from tensorflow.contrib.keras import backend as K
class YAGOConveMultimodel(ModelDesc):
def __init__(self, hyperparams):
super(YAGOConveMultimodel, self).__init__()
self.hyperparams = hyperparams
def _get_inputs(self):
return [InputDesc... | 9,042 | 45.137755 | 120 | py |
mkbe | mkbe-master/MKBE/test/test_runner.py | import sys, tqdm
from tensorpack import *
from tensorpack.callbacks.inference_runner import _inference_context
class TestRunner(callbacks.InferenceRunner):
feed = {
"InferenceTower/emb_keepprob:0": 1.0,
"InferenceTower/fm_keepprob:0": 1.0,
"InferenceTower/mlp_keepprob:0": 1.0,
"Inf... | 1,034 | 33.5 | 85 | py |
mkbe | mkbe-master/MKBE/metrics/metrics.py | import tensorflow as tf
def mrr(higher_values):
pos_index = higher_values + 1
return tf.reduce_mean(1.0/ pos_index)
def hits_n(higher_values, n):
hits_times = tf.cast(higher_values <= (n - 1), tf.float32)
return tf.reduce_mean(hits_times) | 257 | 24.8 | 62 | py |
mkbe | mkbe-master/MKBE/metrics/__init__.py | from .metrics import * | 22 | 22 | 22 | py |
mkbe | mkbe-master/MKBE/train/yago_training.py | from tensorpack import *
class SingleGPUTrainer(train.SimpleTrainer):
def __init__(self, hyperparams):
super(SingleGPUTrainer, self).__init__()
mutable_params = ["emb_keepprob", "fm_keepprob", "mlp_keepprob", "label_smoothing"]
self.feed = dict((k + ":0", hyperparams[k]) for k in mutable_p... | 736 | 35.85 | 91 | py |
mkbe | mkbe-master/MKBE/preprocess/ml100k_preprocess.py | import itertools
import numpy as np
import pandas as pd
# subset can be ["movie_user_rating", "movie_title_rating", "movie_rating", "user_rating", "rating"]
fold = 1
subset = "movie_title_poster_user_rating"
#subset = "movie_title_user_rating"
in_files = {
"user-train": "../code/movielens/ml-100k/u.user",
"m... | 7,432 | 38.748663 | 122 | py |
mkbe | mkbe-master/MKBE/preprocess/yago_preprocess.py | from collections import defaultdict
import numpy as np
import msgpack, msgpack_numpy, os, lmdb
msgpack_numpy.patch()
in_files = {
"train": "../code/YAGO/data/YAGO3-10/train.txt",
"test": "../code/YAGO/data/YAGO3-10/test.txt",
"valid": "../code/YAGO/data/YAGO3-10/valid.txt",
"numerical": "../code/YAGO... | 6,281 | 28.632075 | 106 | py |
mkbe | mkbe-master/MKBE/Evaluation/Evaluation.py | import numpy as np
def Mrr(Score_N, Score):
""" calculate MRR for each sample in test dataset """
S_n = Score_N.tolist()
S = Score_N
for i in Score_N:
S_n = Score_N.tolist()
if np.absolute(i - Score) < 0.0001:
Score_N = np.delete(Score_N, S_n.index(i))
MR = np.append(Sc... | 1,846 | 25.014085 | 120 | py |
mkbe | mkbe-master/MKBE/Evaluation/__init__.py | from .Evaluation import hits, Mrr | 33 | 33 | 33 | py |
mkbe | mkbe-master/MKBE/tasks/train_yago_kb.py | from input_pipeline.yago_input_pipeline import train_dataflow, test_dataflow, profiling_dataflow, profiling_test_df
from models.yago_convE_kb_model import YAGOConveMultimodel
from train.yago_training import SingleGPUTrainer
from test.test_runner import TestRunner
from tensorpack import *
import numpy as np
import tenso... | 2,389 | 28.506173 | 115 | py |
mkbe | mkbe-master/MKBE/tasks/train_ml.py | from models import ml_convE_kb as model
from input_pipeline import negative_sampling as ns
from input_pipeline import dataset_loader as dl
import Evaluation
import tensorflow as tf
import numpy as np
# subset can be ["movie_title_poster_user_rating", "movie_title_user_rating", "movie_title_rating", "movie_rating",
... | 7,193 | 39.189944 | 117 | py |
mkbe | mkbe-master/MKBE/tasks/train_yago.py | import numpy as np
import tensorflow as tf
import input_pipeline.dataset_loader_yago as dl
import models.yago_convE_kb as model
import input_pipeline.negative_sampling_yago as ns
# subset can be ["id", "text_id", "num_id", "image_id", "image_num_id", "image_text_id", "text_num_id", "image_text_num_id"]
subset = "tex... | 3,586 | 32.212963 | 124 | py |
mkbe | mkbe-master/MKBE/tasks/__init__.py | 1 | 0 | 0 | py | |
mkbe | mkbe-master/MKBE/tasks/train_ml_gan_img.py | from input_pipeline.ml_img_loader import get_input_pipeline
from tensorpack import *
from tensorpack.dataflow import *
import os
df = get_input_pipeline(64)
test = dataflow.TestDataSpeed(df)
test.start() | 205 | 21.888889 | 59 | py |
mkbe | mkbe-master/MKBE/input_pipeline/yago_input_pipeline.py | from tensorpack import *
from tensorpack.dataflow import *
from input_pipeline.yago_lmdb_loader import LoaderS, TestLoaderDataflow
def sparse_to_dense(datapoint):
e1, r, e2_train, e2_test = datapoint
return e1, r, e2_train.toarray(), e2_test
def train_dataflow(s_file, idenc_file, batch_size, epoch, gpu_list... | 1,686 | 37.340909 | 83 | py |
mkbe | mkbe-master/MKBE/input_pipeline/yago_lmdb_loader.py | import numpy as np
import msgpack, msgpack_numpy, lmdb, os
from scipy import sparse
from tensorpack import *
msgpack_numpy.patch()
def decode_key(byte_k):
return int(str(byte_k, encoding="utf-8"))
def encode_key(int_k):
return u"{0:0>10}".format(int_k).encode("UTF-8")
class LoaderS:
def __init__(self... | 3,556 | 35.295918 | 119 | py |
mkbe | mkbe-master/MKBE/input_pipeline/negative_sampling.py | import numpy as np
def negative_sampling_aligned(batch, hyperparams, idenc, titles, poster_arr):
# Negative sampling: randomly choose an entity in the dictionary for categorical data,
# or sample from a normal distribution for real numbers
af = "is of_"
e1, r, e2 = batch
rel2id = idenc["rel2id"]
... | 9,866 | 46.210526 | 124 | py |
mkbe | mkbe-master/MKBE/input_pipeline/dataset_loader.py | # Relations used: age, gender, occupation, zip, title, release date, genre, rating(1-5)
import numpy as np
class Dataset:
def __init__(self, files, setname="train"):
setfile, encfile, titles, posters, title_dict = files
setarr = np.load(setfile)
self.idencoders = np.load(encfile).reshape(... | 2,118 | 33.177419 | 91 | py |
mkbe | mkbe-master/MKBE/input_pipeline/__init__.py | from .dataset_loader import Dataset
from .negative_sampling import negative_sampling_aligned, aggregate_sampled_batch, build_gan_feed
from .yago_lmdb_loader import LoaderS | 171 | 56.333333 | 97 | py |
mkbe | mkbe-master/MKBE/input_pipeline/ml_img_loader.py | from tensorpack import *
from tensorpack.dataflow import *
import cv2, os
import numpy as np
class FileReader:
def __init__(self, imgdir, weightsdir):
self.imgrt = imgdir + "{:}.jpg"
self.weights = np.load(weightsdir)
def read_arr_byid(self, movieid):
filename = self.imgrt.format(movi... | 1,120 | 31.028571 | 99 | py |
mkbe | mkbe-master/MKBE/input_pipeline/dataset_loader_yago.py | # Relations used: 0-37, numerical, bio, image
import numpy as np
class Dataset:
def __init__(self, files, setname="train"):
setfile, encfile, texts = files
setarr = np.load(setfile, encoding="latin1")
self.idencoders = np.load(encfile, encoding="latin1").reshape((1))[0]
self.texts... | 2,056 | 30.646154 | 90 | py |
mkbe | mkbe-master/MKBE/input_pipeline/negative_sampling_yago.py | import numpy as np
def negative_sampling_aligned(batch, hyperparams, idenc, texts):
# Negative sampling: randomly choose an entity in the dictionary for categorical data,
# or sample from a normal distribution for real numbers
e1, r, e2 = batch
rel2id = idenc["rel2id"]
# Extract num strips
id... | 3,263 | 39.296296 | 108 | py |
mkbe | mkbe-master/ImgGAN/inputpipe.py | # coding: utf-8
import tensorflow as tf
"""
def read_parse_preproc(filename_queue):
''' read, parse, and preproc single example. '''
with tf.variable_scope('read_parse_preproc'):
reader = tf.WholeFileReader()
_, image_file = reader.read(filename_queue)
image = tf.image.decode_jpeg(image... | 5,543 | 42.653543 | 120 | py |
mkbe | mkbe-master/ImgGAN/utils.py | # coding: utf-8
import tensorflow as tf
import tensorflow.contrib.slim as slim
'''https://stackoverflow.com/questions/37604289/tkinter-tclerror-no-display-name-and-no-display-environment-variable
Matplotlib chooses Xwindows backend by default. You need to set matplotlib do not use Xwindows backend.
- `matplotlib.use('A... | 5,866 | 33.309942 | 127 | py |
mkbe | mkbe-master/ImgGAN/config.py | from models import *
model_zoo = ['EBGAN', 'BEGAN', 'DRAGAN']
def get_model(mtype, name, training):
model = None
if mtype == 'EBGAN':
model = ebgan.EBGAN
elif mtype == 'BEGAN':
model = began.BEGAN
elif mtype == 'CBEGAN':
model = cbegan.BEGAN
elif mtype == 'CBEGANHG':
... | 1,368 | 25.326923 | 106 | py |
mkbe | mkbe-master/ImgGAN/eval.py | #coding: utf-8
import tensorflow as tf
import numpy as np
import utils, cv2
import config, pickle
import os, glob
import scipy.misc
import random
from argparse import ArgumentParser
slim = tf.contrib.slim
def build_parser():
parser = ArgumentParser()
models_str = ' / '.join(config.model_zoo)
parser.add_ar... | 9,114 | 36.204082 | 120 | py |
mkbe | mkbe-master/ImgGAN/convert.py | # coding: utf-8
import tensorflow as tf
import numpy as np
import scipy.misc
import os, cv2
import glob
def _bytes_features(value):
return tf.train.Feature(bytes_list=tf.train.BytesList(value=value))
def _int64_features(value):
return tf.train.Feature(int64_list=tf.train.Int64List(value=value))
def _floa... | 5,321 | 32.055901 | 122 | py |
mkbe | mkbe-master/ImgGAN/ops.py | # coding: utf-8
import tensorflow as tf
slim = tf.contrib.slim
def lrelu(inputs, leak=0.2, scope="lrelu"):
"""
https://github.com/tensorflow/tensorflow/issues/4079
"""
with tf.variable_scope(scope):
f1 = 0.5 * (1 + leak)
f2 = 0.5 * (1 - leak)
return f1 * inputs + f2 * abs(inpu... | 324 | 20.666667 | 56 | py |
mkbe | mkbe-master/ImgGAN/train.py | # coding: utf-8
import tensorflow as tf
from tqdm import tqdm
import numpy as np
import inputpipe as ip
import glob, os, sys, random
from argparse import ArgumentParser
import utils, config, pickle, cv2
def build_parser():
parser = ArgumentParser()
parser.add_argument('--num_epochs', default=75, help='defaul... | 9,960 | 44.072398 | 123 | py |
mkbe | mkbe-master/ImgGAN/models/cbeganhg.py | # coding: utf-8
import tensorflow as tf
import numpy as np
slim = tf.contrib.slim
from utils import expected_shape
import ops
from .basemodel import BaseModel
class BEGAN(BaseModel):
def __init__(self, name, training, D_lr=1e-4, G_lr=1e-4, image_shape=[64, 64, 3], z_dim=64, gamma=0.5, c_dim=200):
self.gam... | 11,498 | 41.120879 | 124 | py |
mkbe | mkbe-master/ImgGAN/models/cbegan.py | # coding: utf-8
import tensorflow as tf
import numpy as np
slim = tf.contrib.slim
from utils import expected_shape
import ops
from .basemodel import BaseModel
class BEGAN(BaseModel):
def __init__(self, name, training, D_lr=1e-4, G_lr=1e-4, image_shape=[64, 64, 3], z_dim=64, gamma=0.5, c_dim=200):
self.gam... | 8,591 | 41.96 | 124 | py |
mkbe | mkbe-master/ImgGAN/models/ecbegan.py | # coding: utf-8
import tensorflow as tf
import numpy as np
slim = tf.contrib.slim
from utils import expected_shape
import ops
from .basemodel import BaseModel
class BEGAN(BaseModel):
def __init__(self, name, training, D_lr=1e-4, G_lr=1e-4, image_shape=[64, 64, 3], z_dim=64, gamma=0.5, c_dim=200):
self.gam... | 9,694 | 42.868778 | 119 | py |
mkbe | mkbe-master/ImgGAN/models/ebgan.py | # coding: utf-8
import tensorflow as tf
slim = tf.contrib.slim
from utils import expected_shape
import ops
from .basemodel import BaseModel
class EBGAN(BaseModel):
def __init__(self, name, training, D_lr=1e-3, G_lr=1e-3, image_shape=[64, 64, 3], z_dim=100,
pt_weight=0.1, margin=20.):
''' The defa... | 5,804 | 44.351563 | 115 | py |
mkbe | mkbe-master/ImgGAN/models/basemodel.py | # coding: utf-8
'''BaseModel for Generative Adversarial Netowrks.
'''
import tensorflow as tf
slim = tf.contrib.slim
class BaseModel(object):
FAKE_MAX_OUTPUT = 12
def __init__(self, name, training, D_lr, G_lr, image_shape=[64, 64, 3], z_dim=100):
self.name = name
self.shape = image_shape
... | 1,113 | 25.52381 | 87 | py |
mkbe | mkbe-master/ImgGAN/models/__init__.py | from os.path import dirname, basename, isfile
import glob
def get_all_modules_cwd():
modules = glob.glob(dirname(__file__)+"/*.py")
return [basename(f)[:-3] for f in modules if isfile(f) and not f.endswith('__init__.py')]
__all__ = get_all_modules_cwd() | 265 | 25.6 | 93 | py |
mkbe | mkbe-master/ImgGAN/models/began.py | # coding: utf-8
import tensorflow as tf
slim = tf.contrib.slim
from utils import expected_shape
import ops
from .basemodel import BaseModel
class BEGAN(BaseModel):
def __init__(self, name, training, D_lr=1e-4, G_lr=1e-4, image_shape=[64, 64, 3], z_dim=64, gamma=0.5):
self.gamma = gamma
self.decay_... | 7,504 | 41.40113 | 119 | py |
UString | UString-master/main.py | #!/usr/bin/env python
# coding: utf-8
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
import torch
import os, time
import argparse
import shutil
from torch.utils.data import DataLoader
from src.Models import UString
from src.eval_tools im... | 23,703 | 48.280665 | 185 | py |
UString | UString-master/demo.py | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
import cv2
import os, sys
import os.path as osp
import argparse
import torch
import torch.nn as nn
from torchvision import models, transforms
from PIL import Image
import matplotlib.pyplot as... | 18,597 | 44.920988 | 152 | py |
UString | UString-master/src/DataLoader.py | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
import numpy as np
import pickle
import torch
from torch.utils.data import Dataset
import networkx
import itertools
class DADDataset(Dataset):
def __init__(self, data_path, feature, phase='train... | 15,669 | 39.386598 | 141 | py |
UString | UString-master/src/utils.py | import math
import numpy as np
# utility functions
def uniform(size, tensor):
stdv = 1.0 / math.sqrt(size)
if tensor is not None:
tensor.data.uniform_(-stdv, stdv)
def glorot(tensor):
stdv = math.sqrt(6.0 / (tensor.size(0) + tensor.size(1)))
if tensor is not None:
tensor.data.uniform_... | 970 | 20.108696 | 68 | py |
UString | UString-master/src/BayesModels.py | import torch
import torch.nn as nn
import torch.nn.functional as F
import math
class Gaussian(object):
def __init__(self, mu, rho):
super().__init__()
self.mu = mu
self.rho = rho
self.normal = torch.distributions.Normal(0,1)
@property
def sigma(self):
return tor... | 3,130 | 38.632911 | 100 | py |
UString | UString-master/src/__init__.py | 0 | 0 | 0 | py | |
UString | UString-master/src/eval_tools.py | import numpy as np
import matplotlib.pyplot as plt
import os
from scipy.interpolate import make_interp_spline
def evaluation(all_pred, all_labels, time_of_accidents, fps=20.0):
"""
:param: all_pred (N x T), where N is number of videos, T is the number of frames for each video
:param: all_labels (N,)
:p... | 7,404 | 43.608434 | 173 | py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.