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
gunpowder
gunpowder-master/docs/build/conf.py
# -*- coding: utf-8 -*- # # gunpowder documentation build configuration file, created by # sphinx-quickstart on Fri Jun 30 12:59:21 2017. # # This file is execfile()d with the current directory set to its # containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # #...
5,592
30.24581
245
py
gunpowder
gunpowder-master/docs/build/_themes/sphinx_rtd_theme/__init__.py
"""Sphinx ReadTheDocs theme. From https://github.com/ryan-roemer/sphinx-bootstrap-theme. """ from os import path __version__ = '0.2.5b2' __version_full__ = __version__ def get_html_theme_path(): """Return list of HTML theme paths.""" cur_dir = path.abspath(path.dirname(path.dirname(__file__))) return c...
522
25.15
96
py
treelstm.pytorch
treelstm.pytorch-master/main.py
from __future__ import division from __future__ import print_function import os import random import logging import torch import torch.nn as nn import torch.optim as optim # IMPORT CONSTANTS from treelstm import Constants # NEURAL NETWORK MODULES/LAYERS from treelstm import SimilarityTreeLSTM # DATA HANDLING CLASSES...
7,610
39.484043
99
py
treelstm.pytorch
treelstm.pytorch-master/config.py
import argparse def parse_args(): parser = argparse.ArgumentParser( description='PyTorch TreeLSTM for Sentence Similarity on Dependency Trees') # data arguments parser.add_argument('--data', default='data/sick/', help='path to dataset') parser.add_argument('--glove', de...
2,532
48.666667
83
py
treelstm.pytorch
treelstm.pytorch-master/scripts/download.py
""" Downloads the following: - Stanford parser - Stanford POS tagger - Glove vectors - SICK dataset (semantic relatedness task) """ from __future__ import print_function import urllib2 import sys import os import zipfile def download(url, dirpath): filename = url.split('/')[-1] filepath = os.path.join(dirpat...
3,938
28.177778
91
py
treelstm.pytorch
treelstm.pytorch-master/scripts/preprocess-sick.py
""" Preprocessing script for SICK data. """ import os import glob def make_dirs(dirs): for d in dirs: if not os.path.exists(d): os.makedirs(d) def dependency_parse(filepath, cp='', tokenize=True): print('\nDependency parsing ' + filepath) dirpath = os.path.dirname(filepath) fil...
3,975
34.185841
87
py
treelstm.pytorch
treelstm.pytorch-master/treelstm/tree.py
# tree object from stanfordnlp/treelstm class Tree(object): def __init__(self): self.parent = None self.num_children = 0 self.children = list() def add_child(self, child): child.parent = self self.num_children += 1 self.children.append(child) def size(self):...
946
26.852941
54
py
treelstm.pytorch
treelstm.pytorch-master/treelstm/Constants.py
PAD = 0 UNK = 1 BOS = 2 EOS = 3 PAD_WORD = '<blank>' UNK_WORD = '<unk>' BOS_WORD = '<s>' EOS_WORD = '</s>'
108
9.9
20
py
treelstm.pytorch
treelstm.pytorch-master/treelstm/utils.py
from __future__ import division from __future__ import print_function import os import math import torch from .vocab import Vocab # loading GLOVE word vectors # if .pth file is found, will load that # else will load from .txt file & save def load_word_vectors(path): if os.path.isfile(path + '.pth') and os.path...
2,376
32.957143
89
py
treelstm.pytorch
treelstm.pytorch-master/treelstm/model.py
import torch import torch.nn as nn import torch.nn.functional as F from . import Constants # module for childsumtreelstm class ChildSumTreeLSTM(nn.Module): def __init__(self, in_dim, mem_dim): super(ChildSumTreeLSTM, self).__init__() self.in_dim = in_dim self.mem_dim = mem_dim sel...
3,286
36.352273
95
py
treelstm.pytorch
treelstm.pytorch-master/treelstm/dataset.py
import os from tqdm import tqdm from copy import deepcopy import torch import torch.utils.data as data from . import Constants from .tree import Tree # Dataset class for SICK dataset class SICKDataset(data.Dataset): def __init__(self, path, vocab, num_classes): super(SICKDataset, self).__init__() ...
2,927
32.655172
82
py
treelstm.pytorch
treelstm.pytorch-master/treelstm/vocab.py
# vocab object from harvardnlp/opennmt-py class Vocab(object): def __init__(self, filename=None, data=None, lower=False): self.idxToLabel = {} self.labelToIdx = {} self.lower = lower # Special entries will not be pruned. self.special = [] if data is not None: ...
2,537
28.172414
81
py
treelstm.pytorch
treelstm.pytorch-master/treelstm/metrics.py
from copy import deepcopy import torch class Metrics(): def __init__(self, num_classes): self.num_classes = num_classes def pearson(self, predictions, labels): x = deepcopy(predictions) y = deepcopy(labels) x = (x - x.mean()) / x.std() y = (y - y.mean()) / y.std() ...
504
23.047619
43
py
treelstm.pytorch
treelstm.pytorch-master/treelstm/__init__.py
from . import Constants from .dataset import SICKDataset from .metrics import Metrics from .model import SimilarityTreeLSTM from .trainer import Trainer from .tree import Tree from . import utils from .vocab import Vocab __all__ = [Constants, SICKDataset, Metrics, SimilarityTreeLSTM, Trainer, Tree, Vocab, utils]
315
27.727273
92
py
treelstm.pytorch
treelstm.pytorch-master/treelstm/trainer.py
from tqdm import tqdm import torch from . import utils class Trainer(object): def __init__(self, args, model, criterion, optimizer, device): super(Trainer, self).__init__() self.args = args self.model = model self.criterion = criterion self.optimizer = optimizer s...
2,384
40.842105
96
py
FastVae_Gpu
FastVae_Gpu-main/run_mm.py
from dataloader import RecData, UserItemData from sampler_gpu_mm import SamplerBase, PopularSampler, MidxUniform, MidxUniPop import torch import torch.optim from torch.optim.lr_scheduler import StepLR from torch.utils.data import DataLoader from vae_models import BaseVAE, VAE_Sampler import argparse import numpy as np ...
10,590
45.862832
172
py
FastVae_Gpu
FastVae_Gpu-main/vae_models.py
import torch import torch.nn as nn import torch.nn.functional as F import time class BaseVAE(nn.Module): def __init__(self, num_item, dims, active='relu', dropout=0.5): """ dims is a list for latent dims """ super(BaseVAE, self).__init__() self.num_item = num_item ...
6,596
38.740964
115
py
FastVae_Gpu
FastVae_Gpu-main/dataloader.py
import pandas as pd from torch.utils.data import IterableDataset, Dataset import torch from torch.utils.data import Dataset, IterableDataset, DataLoader import scipy.io as sci import scipy as sp import random import numpy as np import math import os class RecData(object): def __init__(self, dir, file_name): ...
3,526
35.739583
96
py
FastVae_Gpu
FastVae_Gpu-main/utils.py
import scipy as sp import scipy.sparse as ss import scipy.io as sio import random import numpy as np from typing import List import logging import torch import math from torch.nn.utils.rnn import pad_sequence def get_logger(filename, verbosity=1, name=None): filename = filename + '.txt' level_dict = {0: loggi...
10,977
41.550388
166
py
FastVae_Gpu
FastVae_Gpu-main/sampler_gpu_mm.py
# The cluster algorithmn(K-means) is implemented on the GPU from operator import imod, neg from numpy.core.numeric import indices import scipy.sparse as sps from sklearn import cluster from sklearn.cluster import KMeans import torch import numpy as np import torch.nn as nn from torch._C import device, dtype def kmean...
12,583
40.668874
163
py
KSTER
KSTER-main/setup.py
#!/usr/bin/env python from setuptools import setup, find_packages with open("requirements.txt", encoding="utf-8") as req_fp: install_requires = req_fp.readlines() setup( name='joeynmt', version='1.2', description='Minimalist NMT for educational purposes', author='Jasmijn Bastings and Julia Kreutze...
790
28.296296
68
py
KSTER
KSTER-main/test/__init__.py
0
0
0
py
KSTER
KSTER-main/test/unit/test_vocabulary.py
import unittest import os from joeynmt.vocabulary import Vocabulary class TestVocabulary(unittest.TestCase): def setUp(self): self.file = "test/data/toy/train.de" sent = "Die Wahrheit ist, dass die Titanic – obwohl sie alle " \ "Kinokassenrekorde bricht – nicht gerade die aufregend...
2,599
47.148148
80
py
KSTER
KSTER-main/test/unit/test_data.py
import unittest import numpy as np from joeynmt.data import MonoDataset, TranslationDataset, load_data, \ make_data_iter class TestData(unittest.TestCase): def setUp(self): self.train_path = "test/data/toy/train" self.dev_path = "test/data/toy/dev" self.test_path = "test/data/toy/tes...
7,422
45.685535
80
py
KSTER
KSTER-main/test/unit/test_decoder.py
from torch.nn import GRU, LSTM import torch from joeynmt.decoders import RecurrentDecoder from joeynmt.encoders import RecurrentEncoder from .test_helpers import TensorTestCase class TestRecurrentDecoder(TensorTestCase): def setUp(self): self.emb_size = 10 self.num_layers = 3 self.hidden...
12,263
51.187234
80
py
KSTER
KSTER-main/test/unit/test_loss.py
import torch from joeynmt.loss import XentLoss from .test_helpers import TensorTestCase class TestTransformerUtils(TensorTestCase): def setUp(self): seed = 42 torch.manual_seed(seed) def test_label_smoothing(self): pad_index = 0 smoothing = 0.4 criterion = XentLoss(p...
3,037
34.325581
78
py
KSTER
KSTER-main/test/unit/test_weight_tying.py
from torch.nn import GRU, LSTM import torch import numpy as np from joeynmt.encoders import RecurrentEncoder from .test_helpers import TensorTestCase from joeynmt.model import build_model from joeynmt.vocabulary import Vocabulary import copy class TestWeightTying(TensorTestCase): def setUp(self): self.s...
3,861
34.759259
77
py
KSTER
KSTER-main/test/unit/test_transformer_utils.py
import torch from joeynmt.transformer_layers import PositionalEncoding from .test_helpers import TensorTestCase class TestTransformerUtils(TensorTestCase): def setUp(self): seed = 42 torch.manual_seed(seed) def test_position_encoding(self): batch_size = 2 max_time = 3 ...
595
23.833333
66
py
KSTER
KSTER-main/test/unit/test_batch.py
import torch import random from torchtext.data.batch import Batch as TorchTBatch from joeynmt.batch import Batch from joeynmt.data import load_data, make_data_iter from joeynmt.constants import PAD_TOKEN from .test_helpers import TensorTestCase class TestData(TensorTestCase): def setUp(self): self.trai...
5,692
40.554745
80
py
KSTER
KSTER-main/test/unit/test_model_init.py
from torch.nn import GRU, LSTM import torch from torch import nn import numpy as np from joeynmt.encoders import RecurrentEncoder from .test_helpers import TensorTestCase from joeynmt.model import build_model from joeynmt.vocabulary import Vocabulary import copy class TestModelInit(TensorTestCase): def setUp(se...
1,962
31.180328
75
py
KSTER
KSTER-main/test/unit/test_encoder.py
from torch.nn import GRU, LSTM import torch from joeynmt.encoders import RecurrentEncoder from .test_helpers import TensorTestCase class TestRecurrentEncoder(TensorTestCase): def setUp(self): self.emb_size = 10 self.num_layers = 3 self.hidden_size = 7 seed = 42 torch.manu...
5,086
45.669725
79
py
KSTER
KSTER-main/test/unit/test_search.py
import torch import numpy as np from joeynmt.search import greedy, recurrent_greedy, transformer_greedy from joeynmt.search import beam_search from joeynmt.decoders import RecurrentDecoder, TransformerDecoder from joeynmt.encoders import RecurrentEncoder from joeynmt.embeddings import Embeddings from joeynmt.model imp...
8,723
39.018349
83
py
KSTER
KSTER-main/test/unit/test_knn.py
import sys sys.path.append("../..") from joeynmt.knn import KNNElasticSearch, KNNFaissSearch import time import numpy as np embeddings_path = "embeddings_4.npy" embeddings = np.load(embeddings_path) m_embeddings = np.load(embeddings_path, mmap_mode="r") batch_size = 32 d = 512 n_run = 100 # es_knn = KNNElasticSearc...
1,210
33.6
102
py
KSTER
KSTER-main/test/unit/__init__.py
0
0
0
py
KSTER
KSTER-main/test/unit/test_transformer_decoder.py
import torch from joeynmt.decoders import TransformerDecoder, TransformerDecoderLayer from .test_helpers import TensorTestCase class TestTransformerDecoder(TensorTestCase): def setUp(self): self.emb_size = 12 self.num_layers = 3 self.hidden_size = 12 self.ff_size = 24 sel...
6,322
42.909722
79
py
KSTER
KSTER-main/test/unit/test_transformer_encoder.py
import torch from joeynmt.encoders import TransformerEncoder from .test_helpers import TensorTestCase class TestTransformerEncoder(TensorTestCase): def setUp(self): self.emb_size = 12 self.num_layers = 3 self.hidden_size = 12 self.ff_size = 24 self.num_heads = 4 s...
3,144
40.381579
78
py
KSTER
KSTER-main/test/unit/test_metric.py
import unittest from test.unit.test_helpers import TensorTestCase from joeynmt.metrics import chrf, bleu, token_accuracy class TestMetrics(TensorTestCase): def test_chrf_without_whitespace(self): hyp1 = ["t est"] ref1 = ["tez t"] score1 = chrf(hyp1, ref1, remove_whitespace=True) ...
1,674
30.018519
59
py
KSTER
KSTER-main/test/unit/test_embeddings.py
import torch from joeynmt.embeddings import Embeddings from .test_helpers import TensorTestCase class TestEmbeddings(TensorTestCase): def setUp(self): self.emb_size = 10 self.vocab_size = 11 self.pad_idx = 1 seed = 42 torch.manual_seed(seed) def test_size(self): ...
3,091
38.139241
78
py
KSTER
KSTER-main/test/unit/test_attention.py
import torch from joeynmt.attention import BahdanauAttention, LuongAttention from .test_helpers import TensorTestCase class TestBahdanauAttention(TensorTestCase): def setUp(self): self.key_size = 3 self.query_size = 5 self.hidden_size = 7 seed = 42 torch.manual_seed(seed)...
16,419
42.786667
81
py
KSTER
KSTER-main/test/unit/test_helpers.py
import unittest import torch class TensorTestCase(unittest.TestCase): def assertTensorNotEqual(self, expected, actual): equal = torch.equal(expected, actual) if equal: self.fail("Tensors did match but weren't supposed to: expected {}," " actual {}.".format(expect...
879
34.2
79
py
KSTER
KSTER-main/scripts/average_checkpoints_launcher.py
import os import glob import subprocess subfolder = os.listdir("models")[0] folder = os.path.join("models", subfolder) inputs_str = " ".join(glob.glob("%s/[0-9]*.ckpt" % folder)) output_str = "%s/averaged.ckpt" % folder subprocess.call("python3 scripts/average_checkpoints.py --inputs %s --output %s" % (inputs_str, ou...
342
33.3
120
py
KSTER
KSTER-main/scripts/preprocess_jparacrawl.py
# coding: utf-8 """ Preprocess JParaCrawl """ import os import argparse import pandas as pd import numpy as np import unicodedata from collections import OrderedDict def prepare(data_dir, size, seed=None): dtype = OrderedDict({'source': str, 'probability': float, 'en': str, 'ja': str}) df = pd.read_csv(os.pa...
1,849
36.755102
111
py
KSTER
KSTER-main/scripts/post_process_hypothesis.py
from joeynmt.vocabulary import Vocabulary import os import subprocess import yaml import glob from sacremoses import MosesTokenizer, MosesDetokenizer import spacy from collections import Counter config_path = glob.glob("*.yaml")[0] config = yaml.safe_load(open(config_path, "r", encoding="utf-8")) src_lang = config["d...
6,629
41.774194
168
py
KSTER
KSTER-main/scripts/average_checkpoints.py
#!/usr/bin/env python3 # coding: utf-8 """ Checkpoint averaging Mainly follows: https://github.com/pytorch/fairseq/blob/master/scripts/average_checkpoints.py """ import argparse import collections import torch from typing import List def average_checkpoints(inputs: List[str]) -> dict: """Loads checkpoints fro...
3,018
30.123711
79
py
KSTER
KSTER-main/scripts/plot_validations.py
# coding: utf-8 import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt from matplotlib.backends.backend_pdf import PdfPages import argparse import numpy as np def read_vfiles(vfiles): """ Parse validation report files :param vfiles: list of files :return: """ models = {} ...
3,130
32.308511
79
py
KSTER
KSTER-main/scripts/combiner_average_checkpoints_launcher.py
import os import glob import subprocess import yaml subfolder = os.listdir("models")[0] folder = os.path.join("models", subfolder) files = glob.glob("%s/[0-9]*.ckpt" % folder) ids = sorted([int(f[len(folder)+1:-5]) for f in files]) config_path = glob.glob("*.yaml")[0] config = yaml.safe_load(open(config_path, "r", en...
802
35.5
120
py
KSTER
KSTER-main/scripts/build_vocab.py
#!/usr/bin/env python3 import argparse from collections import OrderedDict import numpy as np def build_vocab(train_paths, output_path): """ Builds the vocabulary. Compatible with Nematus build_dict function, but does not output frequencies and special symbols. :param train_paths: :param outp...
2,034
31.301587
79
py
KSTER
KSTER-main/docs/source/conf.py
# -*- coding: utf-8 -*- # # Configuration file for the Sphinx documentation builder. # # This file does only contain a selection of the most common options. For a # full list see the documentation: # http://www.sphinx-doc.org/en/master/config # -- Path setup ------------------------------------------------------------...
5,375
28.377049
79
py
KSTER
KSTER-main/joeynmt/vocabulary.py
# coding: utf-8 """ Vocabulary module """ from collections import defaultdict, Counter from typing import List import numpy as np from torchtext.data import Dataset from joeynmt.constants import UNK_TOKEN, DEFAULT_UNK_ID, \ EOS_TOKEN, BOS_TOKEN, PAD_TOKEN class Vocabulary: """ Vocabulary represents mapping...
6,887
33.09901
79
py
KSTER
KSTER-main/joeynmt/__main__.py
import argparse from joeynmt.training import train from joeynmt.combiner_training import combiner_train from joeynmt.prediction import test from joeynmt.prediction import translate from joeynmt.prediction import analyze def main(): ap = argparse.ArgumentParser("KSTER") ap.add_argument("mode", choices=["train...
4,404
41.76699
136
py
KSTER
KSTER-main/joeynmt/build_database.py
import torch import numpy as np import logging from hashlib import md5 from joeynmt.prediction import parse_test_args from joeynmt.helpers import load_config, load_checkpoint, get_latest_checkpoint from joeynmt.data import load_data, Dataset, make_data_iter from joeynmt.model import build_model, _DataParallel, Model ...
7,739
39.52356
119
py
KSTER
KSTER-main/joeynmt/prediction.py
# coding: utf-8 """ This modules holds methods for generating predictions from a model. """ import os import sys from typing import List, Optional import logging import numpy as np import json import torch from torchtext.data import Dataset, Field from joeynmt.helpers import bpe_postprocess, check_combiner_cfg, load_...
32,482
41.406005
239
py
KSTER
KSTER-main/joeynmt/constants.py
# coding: utf-8 """ Defining global constants """ UNK_TOKEN = '<unk>' PAD_TOKEN = '<pad>' BOS_TOKEN = '<s>' EOS_TOKEN = '</s>' DEFAULT_UNK_ID = lambda: 0
156
12.083333
26
py
KSTER
KSTER-main/joeynmt/plotting.py
#!/usr/bin/env python from typing import List, Optional import numpy as np # pylint: disable=wrong-import-position import matplotlib matplotlib.use('Agg') from matplotlib import rcParams from matplotlib.figure import Figure import matplotlib.pyplot as plt from matplotlib.backends.backend_pdf import PdfPages def pl...
2,476
30.75641
78
py
KSTER
KSTER-main/joeynmt/batch.py
# coding: utf-8 """ Implementation of a mini-batch. """ import torch class Batch: """Object for holding a batch of data with mask during training. Input is a batch from a torch text iterator. """ # pylint: disable=too-many-instance-attributes def __init__(self, torch_batch, pad_index, use_cuda=Fa...
3,327
32.616162
73
py
KSTER
KSTER-main/joeynmt/loss.py
# coding: utf-8 """ Module to implement training loss """ import torch from torch import nn, Tensor from torch.autograd import Variable class XentLoss(nn.Module): """ Cross-Entropy Loss with optional label smoothing """ def __init__(self, pad_index: int, smoothing: float = 0.0): super().__in...
3,120
38.506329
78
py
KSTER
KSTER-main/joeynmt/embeddings.py
# coding: utf-8 """ Embedding module """ import io import math import logging import torch from torch import nn, Tensor from joeynmt.helpers import freeze_params from joeynmt.vocabulary import Vocabulary logger = logging.getLogger(__name__) class Embeddings(nn.Module): """ Simple embeddings class """ ...
4,157
33.363636
80
py
KSTER
KSTER-main/joeynmt/training.py
# coding: utf-8 """ Training module """ import argparse import time import shutil from typing import List import logging import os import sys import collections import pathlib import numpy as np import torch from torch import Tensor from torch.utils.tensorboard import SummaryWriter from torchtext.data import Dataset...
33,649
40.389914
80
py
KSTER
KSTER-main/joeynmt/model.py
# coding: utf-8 """ Module to represents whole models """ from typing import Callable import logging import torch.nn as nn from torch import Tensor import torch.nn.functional as F from joeynmt.initialization import initialize_model from joeynmt.embeddings import Embeddings from joeynmt.encoders import Encoder, Recurr...
12,260
37.800633
80
py
KSTER
KSTER-main/joeynmt/data.py
# coding: utf-8 """ Data module """ import sys import random import os import os.path from typing import Optional import logging from torchtext.datasets import TranslationDataset from torchtext import data from torchtext.data import Dataset, Iterator, Field from joeynmt.constants import UNK_TOKEN, EOS_TOKEN, BOS_TOKE...
9,111
37.774468
79
py
KSTER
KSTER-main/joeynmt/transformer_layers.py
# -*- coding: utf-8 -*- import math import torch import torch.nn as nn from torch import Tensor # pylint: disable=arguments-differ class MultiHeadedAttention(nn.Module): """ Multi-Head Attention module from "Attention is All You Need" Implementation modified from OpenNMT-py. https://github.com/OpenN...
10,131
32.66113
80
py
KSTER
KSTER-main/joeynmt/faiss_index.py
# -*- coding: utf-8 -*- # create@ 2021-02-04 13:50 from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import faiss import numpy as np from typing import Tuple import re class FaissIndex(object): def __init__(self, f...
4,631
39.631579
145
py
KSTER
KSTER-main/joeynmt/initialization.py
# coding: utf-8 """ Implements custom initialization """ import math import torch import torch.nn as nn from torch import Tensor from torch.nn.init import _calculate_fan_in_and_fan_out def orthogonal_rnn_init_(cell: nn.RNNBase, gain: float = 1.): """ Orthogonal initialization of recurrent weights RNN p...
6,419
35.271186
79
py
KSTER
KSTER-main/joeynmt/builders.py
# coding: utf-8 """ Collection of builder functions """ from typing import Callable, Optional, Generator import torch from torch import nn from torch.optim.lr_scheduler import _LRScheduler, ReduceLROnPlateau, \ StepLR, ExponentialLR from torch.optim import Optimizer from joeynmt.helpers import ConfigurationError ...
12,622
38.446875
80
py
KSTER
KSTER-main/joeynmt/database.py
# -*- coding: utf-8 -*- # create@ 2021-01-26 18:02 from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals from typing import Tuple import numpy as np from joeynmt.faiss_index import FaissIndex class Database(object): ""...
3,496
37.01087
149
py
KSTER
KSTER-main/joeynmt/combiners.py
import torch from torch import nn import torch.nn.functional as F from torch.nn import init import numpy as np import math from typing import Tuple from joeynmt.database import Database, EnhancedDatabase from joeynmt.kernel import Kernel, GaussianKernel, LaplacianKernel class Combiner(nn.Module): def __init__(se...
11,897
46.214286
140
py
KSTER
KSTER-main/joeynmt/metrics.py
# coding: utf-8 """ This module holds various MT evaluation metrics. """ from typing import List import sacrebleu def chrf(hypotheses, references, remove_whitespace=True): """ Character F-score from sacrebleu :param hypotheses: list of hypotheses (strings) :param references: list of references (stri...
2,355
32.657143
83
py
KSTER
KSTER-main/joeynmt/__init__.py
0
0
0
py
KSTER
KSTER-main/joeynmt/search.py
# coding: utf-8 import torch import torch.nn.functional as F from torch import Tensor import numpy as np from joeynmt.decoders import TransformerDecoder from joeynmt.model import Model from joeynmt.batch import Batch from joeynmt.helpers import tile __all__ = ["greedy", "transformer_greedy", "beam_search", "run_batch...
18,708
39.321121
88
py
KSTER
KSTER-main/joeynmt/attention.py
# coding: utf-8 """ Attention modules """ import torch from torch import Tensor import torch.nn as nn import torch.nn.functional as F class AttentionMechanism(nn.Module): """ Base attention class """ def forward(self, *inputs): raise NotImplementedError("Implement this.") class BahdanauAtt...
7,824
33.933036
80
py
KSTER
KSTER-main/joeynmt/helpers.py
# coding: utf-8 """ Collection of helper functions """ import copy import glob import os import os.path import errno import shutil import random import logging from typing import Optional, List import pathlib import numpy as np import pkg_resources import torch from torch import nn, Tensor from torch.utils.tensorboard...
14,240
32.587264
122
py
KSTER
KSTER-main/joeynmt/combiner_training.py
# coding: utf-8 """ Training module """ import argparse import time import shutil from typing import List import logging import os import sys import collections import pathlib import numpy as np import torch from torch import Tensor from torch.utils.tensorboard import SummaryWriter from torchtext.data import Dataset...
34,477
40.893074
89
py
KSTER
KSTER-main/joeynmt/decoders.py
# coding: utf-8 """ Various decoders """ from typing import Optional import torch import torch.nn as nn from torch import Tensor from joeynmt.attention import BahdanauAttention, LuongAttention from joeynmt.encoders import Encoder from joeynmt.helpers import freeze_params, ConfigurationError, subsequent_mask from joey...
23,155
40.647482
80
py
KSTER
KSTER-main/joeynmt/encoders.py
# coding: utf-8 import torch import torch.nn as nn from torch import Tensor from torch.nn.utils.rnn import pack_padded_sequence, pad_packed_sequence from joeynmt.helpers import freeze_params from joeynmt.transformer_layers import \ TransformerEncoderLayer, PositionalEncoding #pylint: disable=abstract-method cla...
8,571
36.432314
80
py
KSTER
KSTER-main/joeynmt/kernel.py
import torch from typing import Tuple, Union class Kernel(object): def __init__(self) -> None: super(Kernel, self).__init__() def similarity(self, distances: torch.Tensor, bandwidth: Union[float, torch.Tensor]) -> torch.Tensor: raise NotImplementedError def compute_example_based_dist...
1,423
40.882353
143
py
wsireg
wsireg-master/setup.py
#!/usr/bin/env python """The setup script.""" from setuptools import find_packages, setup with open('README.rst') as readme_file: readme = readme_file.read() with open('HISTORY.rst') as history_file: history = history_file.read() with open('requirements.txt') as f: requirements = f.read().splitlines() ...
1,572
26.12069
90
py
wsireg
wsireg-master/wsireg/wsireg2d.py
import json import tempfile import time from copy import copy, deepcopy from pathlib import Path from typing import Any, Dict, List, Optional, Tuple, Union from warnings import warn import shutil import numpy as np import yaml from wsireg.parameter_maps.preprocessing import ImagePreproParams from wsireg.parameter_map...
62,774
34.526316
133
py
wsireg
wsireg-master/wsireg/__init__.py
# flake8: noqa from .wsireg2d import WsiReg2D """wsireg.""" __author__ = """Nathan Heath Patterson""" __email__ = 'heath.patterson@vanderbilt.edu' __version__ = '0.3.8'
171
18.111111
44
py
wsireg
wsireg-master/wsireg/reg_transforms/reg_transform.py
from warnings import warn from typing import Optional import numpy as np import SimpleITK as sitk from wsireg.utils.tform_conversion import convert_to_itk class RegTransform: """Container for elastix transform that manages inversion and other metadata. Converts elastix transformation dict to it's SimpleITK r...
6,013
35.448485
94
py
wsireg
wsireg-master/wsireg/reg_transforms/reg_transform_seq.py
import json from pathlib import Path from typing import Any, Dict, List, Optional, Tuple, Union import numpy as np import SimpleITK as sitk from wsireg.reg_transforms.reg_transform import RegTransform from wsireg.utils.tform_utils import ELX_TO_ITK_INTERPOLATORS class RegTransformSeq: """Class to concatenate an...
10,422
33.39934
112
py
wsireg
wsireg-master/wsireg/reg_transforms/__init__.py
from .reg_transform import RegTransform # noqa: F401 from .reg_transform_seq import RegTransformSeq # noqa: F401
115
37.666667
60
py
wsireg
wsireg-master/wsireg/writers/merge_ome_tiff_writer.py
from pathlib import Path from typing import List, Optional, Tuple, Union import cv2 import numpy as np import SimpleITK as sitk from tifffile import TiffWriter from wsireg.reg_images.reg_image import RegImage from wsireg.reg_images.merge_reg_image import MergeRegImage from wsireg.reg_transforms.reg_transform_seq impo...
13,686
35.596257
106
py
wsireg
wsireg-master/wsireg/writers/__init__.py
0
0
0
py
wsireg
wsireg-master/wsireg/writers/ome_tiff_writer.py
from pathlib import Path from typing import List, Optional, Tuple, Union import cv2 import numpy as np import SimpleITK as sitk from tifffile import TiffWriter from wsireg.reg_images.reg_image import RegImage from wsireg.reg_transforms.reg_transform_seq import RegTransformSeq from wsireg.utils.im_utils import ( f...
10,814
35.785714
112
py
wsireg
wsireg-master/wsireg/writers/tiled_ome_tiff_writer.py
import multiprocessing import random import string from concurrent.futures import ThreadPoolExecutor from pathlib import Path from typing import List, Optional, Tuple, Union import dask.array as da import numpy as np import SimpleITK as sitk import zarr from tifffile import TiffWriter from tiler import Tiler from tqdm...
29,657
34.433692
92
py
wsireg
wsireg-master/wsireg/reg_images/czi_reg_image.py
import warnings from typing import Tuple import dask.array as da import numpy as np import SimpleITK as sitk from wsireg.reg_images.reg_image import RegImage from wsireg.utils.im_utils import CziRegImageReader, guess_rgb class CziRegImage(RegImage): def __init__( self, image, image_res, ...
4,216
28.697183
93
py
wsireg
wsireg-master/wsireg/reg_images/sitk_reg_image.py
import warnings import SimpleITK as sitk from wsireg.reg_images.reg_image import RegImage from wsireg.utils.im_utils import ( ensure_dask_array, get_sitk_image_info, guess_rgb, ) class SitkRegImage(RegImage): def __init__( self, image, image_res, mask=None, pr...
2,748
25.432692
93
py
wsireg
wsireg-master/wsireg/reg_images/np_reg_image.py
import warnings import numpy as np import SimpleITK as sitk from wsireg.reg_images.reg_image import RegImage from wsireg.utils.im_utils import ( ensure_dask_array, guess_rgb, preprocess_dask_array, ) class NumpyRegImage(RegImage): def __init__( self, image, image_res, ...
2,969
27.285714
93
py
wsireg
wsireg-master/wsireg/reg_images/reg_image.py
import json from abc import ABC from copy import deepcopy from pathlib import Path from typing import Dict, List, Optional, Tuple, Union import dask.array as da import itk import numpy as np import SimpleITK as sitk from wsireg.parameter_maps.preprocessing import ImagePreproParams from wsireg.reg_shapes import RegSha...
19,721
29.960754
87
py
wsireg
wsireg-master/wsireg/reg_images/merge_reg_image.py
from pathlib import Path from typing import List, Optional, Union from warnings import warn import numpy as np from wsireg.reg_images.loader import reg_image_loader class MergeRegImage: def __init__( self, image_fp: List[Union[Path, str]], image_res: List[Union[int, float]], chan...
2,466
31.038961
92
py
wsireg
wsireg-master/wsireg/reg_images/aics_reg_image.py
import warnings import dask.array as da import numpy as np import SimpleITK as sitk from aicsimageio import AICSImage from wsireg.reg_images.reg_image import RegImage from wsireg.utils.im_utils import ( ensure_dask_array, guess_rgb, preprocess_dask_array, ) class AICSRegImage(RegImage): def __init__...
2,908
25.935185
93
py
wsireg
wsireg-master/wsireg/reg_images/tifffile_reg_image.py
import warnings from typing import List, Tuple import dask.array as da import numpy as np import SimpleITK as sitk from ome_types import from_xml from tifffile import TiffFile from wsireg.reg_images.reg_image import RegImage from wsireg.utils.im_utils import ( get_tifffile_info, guess_rgb, preprocess_dask...
4,762
29.33758
93
py
wsireg
wsireg-master/wsireg/reg_images/__init__.py
from .np_reg_image import NumpyRegImage # noqa: F401 from .sitk_reg_image import SitkRegImage # noqa: F401 from .tifffile_reg_image import TiffFileRegImage # noqa: F401 from .aics_reg_image import AICSRegImage # noqa: F401 from .czi_reg_image import CziRegImage # noqa: F401 from .merge_reg_image import MergeRegIma...
337
47.285714
62
py
wsireg
wsireg-master/wsireg/reg_images/loader.py
from pathlib import Path from typing import Union, Optional, List import numpy as np import dask.array as da import zarr from wsireg.utils.im_utils import ARRAYLIKE_CLASSES, TIFFFILE_EXTS from wsireg.parameter_maps.preprocessing import ImagePreproParams from . import CziRegImage # AICSRegImage, from . import NumpyRegI...
3,482
35.28125
115
py
wsireg
wsireg-master/wsireg/utils/output_utils.py
from typing import Dict, Union from pathlib import Path import re import numpy as np import matplotlib.pyplot as plt def _natural_sort(list_to_sort: list) -> list: """ Sort list account for lack of leading zeroes. """ convert = ( lambda text: int(text) if text.isdigit() else text.lower() )...
7,574
29.668016
117
py
wsireg
wsireg-master/wsireg/utils/tform_utils.py
import json from pathlib import Path from typing import Tuple, Union import itk import numpy as np import SimpleITK as sitk from wsireg.parameter_maps.transformations import ( BASE_AFF_TFORM, BASE_RIG_TFORM, ) from wsireg.reg_transforms.reg_transform import RegTransform from wsireg.utils.itk_im_conversions im...
18,878
30.998305
125
py
wsireg
wsireg-master/wsireg/utils/itk_im_conversions.py
import itk import SimpleITK as sitk def itk_image_to_sitk_image(image): origin = tuple(image.GetOrigin()) spacing = tuple(image.GetSpacing()) direction = itk.GetArrayFromMatrix(image.GetDirection()).flatten() image = sitk.GetImageFromArray( itk.GetArrayFromImage(image), isVector=image....
1,053
29.114286
70
py
wsireg
wsireg-master/wsireg/utils/shape_utils.py
import json import zipfile from copy import deepcopy from pathlib import Path import cv2 import geojson import numpy as np import SimpleITK as sitk from wsireg.reg_transforms.reg_transform import RegTransform from wsireg.utils.tform_utils import wsireg_transforms_to_itk_composite GJ_SHAPE_TYPE = { "polygon": geo...
20,475
30.213415
112
py
wsireg
wsireg-master/wsireg/utils/config_utils.py
import yaml def parse_check_reg_config(yaml_filepath): with open(yaml_filepath, "r") as file: reg_config = yaml.full_load(file) def check_for_key(top_key, check_dict, check_key): if check_dict.get(check_key) is None: raise ValueError(f"{top_key} does not contain an {check_key}") ...
1,985
29.553846
78
py
wsireg
wsireg-master/wsireg/utils/tform_conversion.py
from copy import deepcopy import SimpleITK as sitk def euler_elx_to_itk2d(tform, is_translation=False): euler2d = sitk.Euler2DTransform() if is_translation: elx_parameters = [0] elx_parameters_trans = [float(p) for p in tform['TransformParameters']] elx_parameters.extend(elx_paramete...
3,303
32.714286
79
py