python_code stringlengths 0 4.04M | repo_name stringlengths 7 58 | file_path stringlengths 5 147 |
|---|---|---|
# Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
#
""" Some utilities """
import os
import math
import warnings
import configargparse
import torch
from nets import ConvNe... | AdversarialAndDimensionality-master | utils.py |
# Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
#
import os
import time
import torch
import torch.nn.functional as F
from torch.autograd import grad
from data import CIF... | AdversarialAndDimensionality-master | main.py |
# Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
#
import math
import time
import numpy as np
import scipy.stats as st
from functools import partial
import torch
from torc... | AdversarialAndDimensionality-master | vulnerability.py |
# Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
#
import os
import numpy as np
from PIL import Image
import torch
from torch.utils.data.sampler import SubsetRandomSampler... | AdversarialAndDimensionality-master | data.py |
# Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
#
from functools import reduce
import torch.nn as nn
import torch.nn.functional as F
class Identity(nn.Module):
def ... | AdversarialAndDimensionality-master | nets.py |
#!/usr/bin/env python3
import argparse
import json
import logging
import os
import pickle
import random
import re
from collections import Counter, OrderedDict
from sklearn.cluster import DBSCAN, AffinityPropagation
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.metrics.pairwise import linear... | aroma-paper-artifacts-main | reference/src/main/python/similar.py |
#!/usr/bin/env python
# Copyright (c) Meta Platforms, Inc. and affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import torch
archs = torch.cuda.get_arch_list()
archs = [arch[3:] for arch in archs if arch.startswith('sm_')]
print... | baspacho-main | cmake/get_torch_cuda_archs.py |
#!/usr/bin/env python
"""TODO."""
from __future__ import print_function
import numbskull
from numbskull.numbskulltypes import *
import numpy as np
def factor(f, args):
"""THIS IS A DOCSTRING."""
if f == FUNC_IMPLY_NATURAL:
# TODO
pass
elif f == FUNC_OR:
return 1 if any(args) else... | numbskull-master | loadfg.py |
#!/usr/bin/env python
"""TODO."""
from numbskull import numbskull
args = ['test',
'-l', '100',
'-i', '100',
'-t', '10',
'-s', '0.01',
'--regularization', '2',
'-r', '0.1',
'--quiet']
ns = numbskull.load(args)
ns.learning()
ns.inference()
print(ns.factorGraphs[0... | numbskull-master | test.py |
#!/usr/bin/env python
"""This tests learning for labelling functions."""
from __future__ import print_function, absolute_import
import numpy as np
import numbskull
from numbskull.numbskulltypes import *
import math
def index_to_values(index, num_lf):
value = [0] * (1 + num_lf)
value[0] = index % 2
index... | numbskull-master | test_lf_learning.py |
"""For pip."""
from setuptools import setup, find_packages
exec(open('numbskull/version.py').read())
setup(
name='numbskull',
version=__version__,
description='sample away',
packages=find_packages(),
install_requires=[
'future',
'futures; python_version == "2.7"',
],
entry_... | numbskull-master | setup.py |
#!/usr/bin/env python
from __future__ import print_function
from distutils.dir_util import mkpath
import sys
import os
import shutil
import subprocess
def generate(directory, degree, copies):
print("Generating " + directory + "...")
sys.stdout.flush()
try:
shutil.rmtree(directory)
except:
... | numbskull-master | experiments/intro/generate.py |
#!/usr/bin/env python
from __future__ import print_function
copies = 10
f = open("input/p.tsv", "w")
f.write("0\t\\N\n")
f.close()
f = open("input/voter_voted_for.tsv", "w")
index = 0
for i in range(copies):
f.write(str(i) + "\t0\n")
f.close()
f = open("input/v.tsv", "w")
for i in range(copies):
f.write(str... | numbskull-master | experiments/partitionable_and_vote/generate.py |
#!/usr/bin/env python
from __future__ import print_function
from distutils.dir_util import mkpath
import sys
import os
import shutil
import subprocess
import time
child_processes = {}
def generate(directory, propositions, voters_per_proposition, copies,
FNULL):
print("Generating " + directory + "..... | numbskull-master | experiments/tradeoff/generate.py |
# -*- coding: utf-8 -*-
#
# Numbskull documentation build configuration file, created by
# sphinx-quickstart on Fri Aug 26 17:55:24 2016.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
#... | numbskull-master | docs/source/conf.py |
#!/usr/bin/env python
"""Script to run distributed experiments."""
import numbskull_master
import sys
if __name__ == "__main__":
n_var = 1260000
machines = 4
threads_per_machine = 1
learning_epochs = 10
inference_epochs = 10
f = open("intro_degree.dat", "w")
f.write("degree\tcopies\tmaste... | numbskull-master | salt/src/experiment_intro_degree.py |
#!/usr/bin/env python
"""Script to run distributed experiments."""
import numbskull_master
if __name__ == "__main__":
application_dir = "/dfs/scratch0/bryanhe/congress6/"
machines = 1
threads_per_machine = 1
learning_epochs = 100
inference_epochs = 100
f = open("congress.dat", "w")
for m... | numbskull-master | salt/src/experiment.py |
"""TODO."""
from __future__ import print_function
import numbskull
from numbskull.numbskulltypes import *
import numbskull.inference
import numpy as np
import codecs
import numba
import time
import networkx as nx
import nxmetis
# Commands from master to minions (Tags)
ASSIGN_ID = 'ASSIGN_ID'
INIT_NS = 'INIT_NS'
LOAD_... | numbskull-master | salt/src/messages.py |
"""TODO."""
# Import python libs
from __future__ import absolute_import
import logging
import sys
import os
import time
import pydoc
import urlparse
import traceback
# libs for server
import msgpack
import socket
import errno
import signal
# Import salt libs
import salt.utils.event
import salt.utils
import salt.payl... | numbskull-master | salt/src/numbskull_minion_server.py |
"""TODO."""
from __future__ import absolute_import
from salt.utils.async import SyncWrapper
from salt.transport.client import AsyncChannel
from salt.transport.tcp import SaltMessageClient
import msgpack
import socket
import weakref
import logging
# Import Salt Libs
import salt.payload
import salt.exceptions
import s... | numbskull-master | salt/src/numbskull_master_client.py |
"""TODO."""
# Import python libs
from __future__ import print_function, absolute_import
import json
import logging
import sys
import os
import time
import argparse
import numpy as np
import codecs
import pydoc
import psycopg2
import urlparse
import numpy as np
import traceback
# Import salt libs
import salt.utils.ev... | numbskull-master | salt/src/numbskull_minion.py |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""TODO."""
# Import python libs
from __future__ import print_function, absolute_import
import json
import logging
import os.path
import numbskull
from numbskull import numbskull
from numbskull.numbskulltypes import *
import argparse
import sys
import subprocess
import nu... | numbskull-master | salt/src/numbskull_master.py |
"""TODO."""
from __future__ import print_function, absolute_import
import numba
from numba import jit
import numpy as np
# HELPER METHODS #
def dataType(i):
"""TODO."""
return {0: "Boolean",
1: "Categorical"}.get(i, "Unknown")
@jit(nopython=True, cache=True)
def compute_var_map(variables, facto... | numbskull-master | numbskull/dataloading.py |
__version__ = "0.1.1"
| numbskull-master | numbskull/version.py |
"""TODO."""
from __future__ import print_function, absolute_import
import sys
import numpy as np
from numbskull.inference import *
from numbskull.learning import *
from numbskull.timer import Timer
import concurrent.futures
from concurrent.futures import ThreadPoolExecutor
def run_pool(threadpool, threads, func, arg... | numbskull-master | numbskull/factorgraph.py |
"""TODO."""
from __future__ import print_function, absolute_import
import time
class Timer:
"""TODO."""
def __enter__(self):
"""TODO."""
self.start = time.time()
return self
def __exit__(self, *args):
"""TODO."""
self.end = time.time()
self.interval = sel... | numbskull-master | numbskull/timer.py |
"""inference and learning for factor graphs"""
from .numbskull import NumbSkull
from .numbskull import main
from .version import __version__
__all__ = ('numbskull', 'factorgraph', 'timer')
| numbskull-master | numbskull/__init__.py |
#!/usr/bin/env python
"""TODO: This is a docstring."""
from __future__ import print_function, absolute_import
from past.builtins import long
import os
import sys
import argparse
import numbskull.factorgraph
from numbskull.factorgraph import FactorGraph
from numbskull.dataloading import *
from numbskull.numbskulltypes... | numbskull-master | numbskull/numbskull.py |
#!/usr/bin/env python
"""TODO."""
from __future__ import print_function
import zmq
import sys
import time
import argparse
import gibbs
import numpy as np
def send_array(socket, A, flags=0, copy=True, track=False):
"""TODO: send a numpy array with metadata."""
md = dict(
dtype=str(A.dtype),
s... | numbskull-master | numbskull/distributed.py |
"""TODO."""
from __future__ import print_function, absolute_import
import numpy as np
# TODO (shared with DW): space optimization:
# 1. use smaller ints for some fields
# 2. replace a[x].length with a[x+1].offset - a[x].offset
Meta = np.dtype([('weights', np.int64),
('variables', np.int64),
... | numbskull-master | numbskull/numbskulltypes.py |
"""TODO."""
from __future__ import print_function, absolute_import
import numba
from numba import jit
import numpy as np
import math
@jit(nopython=True, cache=True, nogil=True)
def gibbsthread(shardID, nshards, var_copy, weight_copy, weight, variable,
factor, fmap, vmap, factor_index, Z, cstart,
... | numbskull-master | numbskull/inference.py |
"""TODO."""
from __future__ import print_function, absolute_import
import numba
from numba import jit
import numpy as np
import math
import random
from numbskull.inference import draw_sample, eval_factor
@jit(nopython=True, cache=True, nogil=True)
def learnthread(shardID, nshards, step, regularization, reg_param, tr... | numbskull-master | numbskull/learning.py |
"""TODO."""
from .numbskull import main
main()
| numbskull-master | numbskull/__main__.py |
from setuptools import setup
setup(
name='pytorch_radon',
version='0.1.0',
author='Philipp Ernst',
author_email='phil23940@yahoo.de',
packages=['pytorch_radon'],
url='https://github.com/phernst/pytorch_radon.git',
license='MIT',
description='Pytorch implementation of scikit-image\'s rad... | pytorch_radon-master | setup.py |
import unittest
from pytorch_radon.utils import PI, SQRT2, deg2rad
import numpy as np
class TestStackgram(unittest.TestCase):
def test_pi(self):
self.assertAlmostEqual(PI.item(), np.pi, places=6)
def test_sqrt2(self):
self.assertAlmostEqual(SQRT2.item(), np.sqrt(2), places=6)
def test_deg... | pytorch_radon-master | tests/test_utils.py |
import unittest
from pytorch_radon import Radon, IRadon
import torch
class TestRadon(unittest.TestCase):
def test_radon_iradon_circle(self):
img = torch.zeros(1,1,256,256)
img[:, :, 120:130, 120:130] = 1
circle = True
theta = torch.arange(180)
r = Radon(img.shape[2], theta, ... | pytorch_radon-master | tests/test_radon.py |
pytorch_radon-master | tests/__init__.py | |
import unittest
from pytorch_radon import Radon, IRadon, Stackgram, IStackgram
import torch
class TestStackgram(unittest.TestCase):
def test_stackgram_istackgram_circle(self):
img = torch.zeros(1,1,256,256)
img[:, :, 120:130, 120:130] = 1
circle = True
theta = torch.arange(180)
... | pytorch_radon-master | tests/test_stackgram.py |
import unittest
from pytorch_radon import Radon, IRadon
from pytorch_radon.filters import RampFilter, HannFilter, LearnableFilter
from pytorch_radon.filters import RampButterflyFilter, HannButterflyFilter
import torch
class TestStackgram(unittest.TestCase):
def test_ramp_filter(self):
img = torch.zeros(1,1... | pytorch_radon-master | tests/test_filters.py |
from .radon import Radon, IRadon
from .stackgram import Stackgram, IStackgram | pytorch_radon-master | pytorch_radon/__init__.py |
import torch
# constants
PI = 4*torch.ones(1).atan()
SQRT2 = (2*torch.ones(1)).sqrt()
def fftfreq(n):
val = 1.0/n
results = torch.zeros(n)
N = (n-1)//2 + 1
p1 = torch.arange(0, N)
results[:N] = p1
p2 = torch.arange(-(n//2), 0)
results[N:] = p2
return results*val
def deg2rad(x):
re... | pytorch_radon-master | pytorch_radon/utils.py |
import torch
from torch import nn
import torch.nn.functional as F
from .utils import PI, SQRT2, deg2rad
from .filters import RampFilter
class Radon(nn.Module):
def __init__(self, in_size, theta=None, circle=True):
super(Radon, self).__init__()
self.circle = circle
self.theta = theta
... | pytorch_radon-master | pytorch_radon/radon.py |
import torch
from torch import nn
import torch.nn.functional as F
from .utils import SQRT2, deg2rad
class Stackgram(nn.Module):
def __init__(self, out_size, theta=None, circle=True, mode='nearest'):
super(Stackgram, self).__init__()
self.circle = circle
self.theta = theta
if theta ... | pytorch_radon-master | pytorch_radon/stackgram.py |
import torch
from torch import nn
import torch.nn.functional as F
from .utils import PI, fftfreq
class AbstractFilter(nn.Module):
def __init__(self):
super(AbstractFilter, self).__init__()
def forward(self, x):
input_size = x.shape[2]
projection_size_padded = \
max(64, int... | pytorch_radon-master | pytorch_radon/filters.py |
from setuptools import find_packages, setup
setup(
name="tabi",
version="0.0.1",
author="Megan Leszczynski",
author_email="mleszczy@stanford.edu",
packages=find_packages(),
)
| tabi-main | setup.py |
import argparse
from tabi.utils.utils import str2bool
parser = argparse.ArgumentParser(add_help=False)
general_args = parser.add_argument_group("general_args")
general_args.add_argument(
"--verbose", type=str2bool, default="False", help="Print debug information"
)
general_args.add_argument(
"--distributed",
... | tabi-main | tabi/config.py |
ENT_START = "[unused1]"
MENTION_START = "[unused2]"
MENTION_END = "[unused3]"
| tabi-main | tabi/constants.py |
tabi-main | tabi/__init__.py | |
"""Extract entity embeddings from a trained biencoder model."""
import argparse
import logging
import os
import numpy as np
import torch
import torch.nn as nn
from torch.utils.data import DataLoader
from tqdm import tqdm
from tabi.config import parser
from tabi.data import EntityDataset
from tabi.models.biencoder im... | tabi-main | tabi/extract_entity.py |
"""Preprocesses entity data into memory mapped file to reduce memory usage by dataloaders."""
import argparse
import logging
import os
import numpy as np
import torch
from torch.utils.data import DataLoader
from tqdm import tqdm
from tabi.config import parser
from tabi.data import EntityDataset
from tabi.utils.train... | tabi-main | tabi/preprocess_entity.py |
"""Train biencoder model for entity retrieval."""
import argparse
import logging
import math
import os
import time
import torch
import torch.distributed as dist
import torch.nn as nn
from torch.utils.data import DataLoader
from torch.utils.tensorboard import SummaryWriter
from tqdm import tqdm
from tabi.config impor... | tabi-main | tabi/train.py |
"""Retrieve candidates for evaluation or hard negative sampling."""
import argparse
import logging
import os
import torch
import torch.distributed as dist
from torch.utils.data import DataLoader
from tqdm import tqdm
from tabi.config import parser
from tabi.data import EntityLinkingDataset
from tabi.models.biencoder... | tabi-main | tabi/eval.py |
import json
import logging
import os
from collections import defaultdict
from typing import Optional
import numpy as np
import torch
import torch.nn.functional as F
from transformers import AutoTokenizer
from transformers import logging as tf_logging
import tabi.utils.data_utils as data_utils
import tabi.utils.utils ... | tabi-main | tabi/data.py |
import logging
import math
import random
import numpy as np
import torch
import torch.distributed as dist
import torch.nn as nn
from transformers.optimization import AdamW
logger = logging.getLogger(__name__)
def get_type_label_mask(labels, type_equivalence="strict"):
"""Generate the mask indicating which queri... | tabi-main | tabi/utils/train_utils.py |
tabi-main | tabi/utils/__init__.py | |
import json
import logging
import pickle
import unicodedata
from collections import Counter
import jsonlines
import numpy as np
import torch
import torch.nn.functional as F
from tabi.constants import MENTION_END, MENTION_START
logger = logging.getLogger(__name__)
def load_neg_samples(neg_sample_file, num_negatives... | tabi-main | tabi/utils/data_utils.py |
import logging
import os
import pickle
import subprocess
import sys
import time
from collections import Counter, defaultdict
import jsonlines
import numpy as np
import torch
import ujson
from torch.nn.modules.utils import consume_prefix_in_state_dict_if_present
from tqdm import tqdm
logger = logging.getLogger(__name_... | tabi-main | tabi/utils/utils.py |
tabi-main | tabi/models/__init__.py | |
import torch
import torch.nn as nn
import tabi.utils.train_utils as train_utils
class TABiLoss(nn.Module):
"""
Type-Aware Bi-encoders (TABi) loss.
"""
def __init__(self, temperature=0.01, alpha=0.1, type_equivalence="strict"):
super(TABiLoss, self).__init__()
self.temperature = tempe... | tabi-main | tabi/models/losses.py |
import logging
import torch.nn.functional as F
from torch import nn
from transformers import AutoModel
logger = logging.getLogger()
class Encoder(nn.Module):
def __init__(self, model_name: str = "bert-base-uncased") -> None:
super().__init__()
logger.info(f"Using encoder model: {model_name}")
... | tabi-main | tabi/models/layers.py |
import logging
import numpy as np
import torch
import torch.distributed as dist
import torch.nn as nn
import torch.nn.functional as F
from tabi.models.layers import Aggregator, Encoder
from tabi.models.losses import TABiLoss
from tabi.utils.train_utils import first_nonzero, gather_embs
logger = logging.getLogger(__n... | tabi-main | tabi/models/biencoder.py |
import subprocess
# set hyperparameters
# number of epochs for each round of sampling
n_epochs = 1
# first epoch is in-batch negatives
num_neg_rounds = 3
# tabi-specific
type_weight = 0.1
# model params
max_context_length = 32
lr = 3e-4
temperature = 0.05
add_types_in_desc = False
seed = 1234
batch_size = 4096
eva... | tabi-main | scripts/run_kilt_data.py |
import subprocess
# set hyperparameters
# number of epochs for each round of sampling
n_epochs = 1
# first epoch is in-batch negatives
num_neg_rounds = 3
# tabi-specific
type_weight = 0.1
# model params
max_context_length = 32
lr = 1e-5
temperature = 0.05
add_types_in_desc = True
seed = 1234
batch_size = 32
eval_b... | tabi-main | scripts/run_sample_cpu.py |
import subprocess
# set hyperparameters
# number of epochs for each round of sampling
n_epochs = 1
# first epoch is in-batch negatives
num_neg_rounds = 3
# tabi-specific
type_weight = 0.1
# model params
max_context_length = 32
lr = 1e-5
temperature = 0.05
add_types_in_desc = True
seed = 1234
batch_size = 32
eval_b... | tabi-main | scripts/run_sample.py |
"""Convert KILT-formatted jsonlines files to TABi-formatted jsonlines files."""
import argparse
import glob
import logging
import os
import jsonlines
from tqdm import tqdm
from tabi.utils.data_utils import load_entity_data
logger = logging.getLogger(__name__)
logging.basicConfig(
level=logging.INFO,
format=... | tabi-main | scripts/preprocess_kilt.py |
import argparse
import logging
from collections import defaultdict
from string import punctuation
import torch
from termcolor import colored
from transformers import AutoTokenizer
from transformers import logging as hf_logging
from tabi.constants import ENT_START
from tabi.models.biencoder import Biencoder
from tabi.... | tabi-main | scripts/demo.py |
import subprocess
# set hyperparameters
# number of epochs for each round of sampling
n_epochs = 1
# first epoch is in-batch negatives
num_neg_rounds = 3
# tabi-specific
type_weight = 0.1
# model params
max_context_length = 32
lr = 3e-4
temperature = 0.05
add_types_in_desc = False
seed = 1234
batch_size = 4096
eva... | tabi-main | scripts/run_blink_data.py |
import glob
from os.path import basename
import setuptools
from setuptools import find_namespace_packages
setuptools.setup(
name="anchor", version="0.0.1", author="Megan Leszczynski", packages=find_namespace_packages()
)
| anchor-stability-master | setup.py |
anchor-stability-master | tests/__init__.py | |
import unittest
from unittest.mock import Mock, patch
import numpy as np
import utils
from scipy.linalg import orthogonal_procrustes
from anchor.embedding import Embedding
class EmbeddingTest(unittest.TestCase):
def test_save_load(self):
# save embedding
vecs = np.array([[0, 1, 2], [3, 4, 5]])
... | anchor-stability-master | tests/test_embedding.py |
import subprocess
import numpy as np
def clean_files(filename):
try:
subprocess.check_output("rm -f %s" % filename, shell=True)
except OSError as e:
print(e)
pass
| anchor-stability-master | tests/utils.py |
"""
Main analysis file to compute the embedding distance measures and downstream measures between pairs
of embeddings and save the results to panda dataframes.
"""
import argparse
import glob
import os
import pickle
import multiprocessing as mp
import numpy as np
import pandas as pd
from anchor.embedding import Embe... | anchor-stability-master | scripts/analysis/dim_stability_analysis.py |
"""
Generates the selection criterion results
-- requires data file with embedding distance and disagreement
between pairs of embeddings as input.
"""
import argparse
import csv
import numpy as np
import pandas as pd
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument('--emb_metrics', typ... | anchor-stability-master | scripts/analysis/selection_criterion.py |
"""
Save the high-precision, full-dimensional embeddings needed for the eigenspace instability measure
in advance for more efficient analysis.
"""
from anchor.embedding import Embedding
import argparse
import pickle
def main():
parser = argparse.ArgumentParser()
parser.add_argument('--algo', type=str, help='Embeddi... | anchor-stability-master | scripts/analysis/create_anchors.py |
"""
Fits linear-log models to the instability v. memory, instability v. dimension,
and instability v. precision trends.
"""
import argparse
import pandas as pd
import numpy as np
import functools
import scipy.stats
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument('--csv-files', type=st... | anchor-stability-master | scripts/analysis/fit_trend.py |
"""
Utils file for analysis.
"""
import os
import subprocess
def check_ner_complete(modelpath1, modelpath2):
""" Checks that the NER task is complete by locating the final-model artifact. """
file1_final = f"{modelpath1}/final-model.pt"
file2_final = f"{modelpath2}/final-model.pt"
assert os.path.isfil... | anchor-stability-master | scripts/analysis/utils.py |
"""
Generates the csvs of all of the embedding and downstream results.
"""
import argparse
import pandas as pd
import numpy as np
# keep track of all the optimal parameters found from the grid search
optimal_wiki = {
('mc', 'la_sst_no_emb_norm'): 0.001,
('mc', 'la_subj_no_emb_norm'): 0.1,
('mc... | anchor-stability-master | scripts/analysis/gather_results.py |
"""
Computes the distance to the oracle when given a selection of pairs at
the same memory budget and must select the pair which attains the lowest
embedding distance measure.
"""
import pandas as pd
import argparse
import csv
import numpy as np
def parse_args():
parser = argparse.ArgumentParser()
parser.add_... | anchor-stability-master | scripts/analysis/diff_to_oracle.py |
"""
Generates the Spearman correlations between the embedding and downstream measures.
"""
import argparse
import csv
import numpy as np
import pandas as pd
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument('--csv-file', type=str, required=True,
help='CSV file with pair results ... | anchor-stability-master | scripts/analysis/get_correlation.py |
"""
Run the embedding compression using smallfry's implementation.
"""
from smallfry.compress import compress_uniform
from smallfry.utils import load_embeddings, save_embeddings
import argparse
import io
import numpy as np
import os
import sys
from anchor.embedding import Embedding
def parse_args():
parser = ar... | anchor-stability-master | scripts/embedding_generation/gen_compressed.py |
"""
Generate commands for compressing embeddings.
"""
import argparse
import pickle
def parse_args():
parser = argparse.ArgumentParser(description="")
parser.add_argument(
"--resultdir1",
type=str,
required=True,
)
parser.add_argument(
"--resultdir2",
type=str,
... | anchor-stability-master | scripts/embedding_generation/compression_experiment_wiki.py |
"""
Downstream model training/prediction on top of an embedding; called from gen_model_cmds.
"""
import argparse
import logging
import glob
import numpy as np
import os
import random
import sys
import torch
from third_party.sentence_classification.train_classifier import train_sentiment
from third_party.flair.ner imp... | anchor-stability-master | scripts/model_training/train_downstream.py |
"""
Generate commands for model training for a list of embeddings.
"""
import argparse
import glob
import os
import sys
def parse_args():
parser = argparse.ArgumentParser(description='')
parser.add_argument('--homedir', type=str, help='Root directory of code', required=True)
parser.add_argument('--python'... | anchor-stability-master | scripts/model_training/gen_model_cmds.py |
"""
Embedding class with embedding distance measures.
modified from https://github.com/williamleif/histwords/blob/master/representations/embedding.py
"""
import copy
import io
import logging
import numpy as np
import os
from scipy import spatial
from scipy.linalg import orthogonal_procrustes
from sklearn.neighbors im... | anchor-stability-master | anchor/embedding.py |
anchor-stability-master | anchor/__init__.py | |
"""
Utils file.
"""
import logging
import time
from datetime import timedelta
def load_vocab_list(vocab_file):
vocab = []
fin = open(vocab_file, "r", encoding="utf-8")
for line in fin:
try:
w, _ = line.rstrip().split(' ')
vocab.append(w)
except:
print(l... | anchor-stability-master | anchor/utils.py |
import matplotlib
import matplotlib.pyplot as plt
import pandas
markers = ['s', 'v', '^', '<', '>', 'o']
def plt_single(df, vals, val_tag, xtag, dist, ylog=False, ylabel='', xlabel='', title='', val_tag_label='', legend=False, color='C4', marker='s', line_label=None):
if val_tag_label == '':
val_tag_labe... | anchor-stability-master | notebooks/plot_utils.py |
"""Train Knowledge Graph embeddings for link prediction."""
import argparse
import json
import logging
import os
import torch
import torch.optim
import models
import optimizers.regularizers as regularizers
from datasets.kg_dataset import KGDataset
from models import all_models
from optimizers.kg_optimizer import KGO... | KGEmb-master | run.py |
"""Evaluation script."""
import argparse
import json
import os
import torch
import models
from datasets.kg_dataset import KGDataset
from utils.train import avg_both, format_metrics
parser = argparse.ArgumentParser(description="Test")
parser.add_argument(
'--model_dir',
help="Model path"
)
def test(model_d... | KGEmb-master | test.py |
"""Dataset class for loading and processing KG datasets."""
import os
import pickle as pkl
import numpy as np
import torch
class KGDataset(object):
"""Knowledge Graph dataset class."""
def __init__(self, data_path, debug):
"""Creates KG dataset object for data loading.
Args:
d... | KGEmb-master | datasets/kg_dataset.py |
KGEmb-master | datasets/__init__.py | |
"""Knowledge Graph dataset pre-processing functions."""
import collections
import os
import pickle
import numpy as np
def get_idx(path):
"""Map entities and relations to unique ids.
Args:
path: path to directory with raw dataset files (tab-separated train/valid/test triples)
Returns:
ent2i... | KGEmb-master | datasets/process.py |
KGEmb-master | utils/__init__.py | |
"""Hyperbolic operations utils functions."""
import torch
MIN_NORM = 1e-15
BALL_EPS = {torch.float32: 4e-3, torch.float64: 1e-5}
# ################# MATH FUNCTIONS ########################
class Artanh(torch.autograd.Function):
@staticmethod
def forward(ctx, x):
x = x.clamp(-1 + 1e-5, 1 - 1e-5)
... | KGEmb-master | utils/hyperbolic.py |
"""Training utils."""
import datetime
import os
def get_savedir(model, dataset):
"""Get unique saving directory name."""
dt = datetime.datetime.now()
date = dt.strftime("%m_%d")
save_dir = os.path.join(
os.environ["LOG_DIR"], date, dataset,
model + dt.strftime('_%H_%M_%S')
)
os... | KGEmb-master | utils/train.py |
"""Euclidean operations utils functions."""
import torch
def euc_sqdistance(x, y, eval_mode=False):
"""Compute euclidean squared distance between tensors.
Args:
x: torch.Tensor of shape (N1 x d)
y: torch.Tensor of shape (N2 x d)
eval_mode: boolean
Returns:
torch.Tensor o... | KGEmb-master | utils/euclidean.py |
from .complex import *
from .euclidean import *
from .hyperbolic import *
all_models = EUC_MODELS + HYP_MODELS + COMPLEX_MODELS
| KGEmb-master | models/__init__.py |
"""Hyperbolic Knowledge Graph embedding models where all parameters are defined in tangent spaces."""
import numpy as np
import torch
import torch.nn.functional as F
from torch import nn
from models.base import KGModel
from utils.euclidean import givens_rotations, givens_reflection
from utils.hyperbolic import mobius_... | KGEmb-master | models/hyperbolic.py |
"""Euclidean Knowledge Graph embedding models where embeddings are in complex space."""
import torch
from torch import nn
from models.base import KGModel
COMPLEX_MODELS = ["ComplEx", "RotatE"]
class BaseC(KGModel):
"""Complex Knowledge Graph Embedding models.
Attributes:
embeddings: complex embeddi... | KGEmb-master | models/complex.py |
"""Base Knowledge Graph embedding model."""
from abc import ABC, abstractmethod
import torch
from torch import nn
class KGModel(nn.Module, ABC):
"""Base Knowledge Graph Embedding model class.
Attributes:
sizes: Tuple[int, int, int] with (n_entities, n_relations, n_entities)
rank: integer for... | KGEmb-master | models/base.py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.