repo
stringlengths
1
99
file
stringlengths
13
215
code
stringlengths
12
59.2M
file_length
int64
12
59.2M
avg_line_length
float64
3.82
1.48M
max_line_length
int64
12
2.51M
extension_type
stringclasses
1 value
ChineseGLUE
ChineseGLUE-master/baselines/models_pytorch/classifier_pytorch/transformers/modeling_xlnet.py
# coding=utf-8 # Copyright 2018 Google AI, Google Brain and Carnegie Mellon University Authors and the HuggingFace Inc. team. # Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the Lice...
72,560
52.002922
169
py
ChineseGLUE
ChineseGLUE-master/baselines/models_pytorch/classifier_pytorch/transformers/modeling_xlm.py
# coding=utf-8 # Copyright 2019-present, Facebook, Inc and the HuggingFace Inc. team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Un...
45,543
50.34611
163
py
ChineseGLUE
ChineseGLUE-master/baselines/models_pytorch/classifier_pytorch/transformers/modeling_ctrl.py
# coding=utf-8 # Copyright 2018 Salesforce and HuggingFace Inc. team. # Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # h...
23,436
47.22428
134
py
ChineseGLUE
ChineseGLUE-master/baselines/models_pytorch/classifier_pytorch/transformers/tokenization_transfo_xl.py
# coding=utf-8 # Copyright 2018 Google AI, Google Brain and Carnegie Mellon University Authors and the HuggingFace Inc. team. # Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the Lice...
21,824
36.62931
133
py
ChineseGLUE
ChineseGLUE-master/baselines/models_pytorch/classifier_pytorch/transformers/modeling_transfo_xl_utilities.py
# coding=utf-8 # Copyright 2018 Google AI, Google Brain and Carnegie Mellon University Authors and the HuggingFace Inc. team. # Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the Lice...
13,568
39.747748
132
py
ChineseGLUE
ChineseGLUE-master/baselines/models_pytorch/classifier_pytorch/transformers/modeling_roberta.py
# coding=utf-8 # Copyright 2018 The Google AI Language Team Authors and The HuggingFace Inc. team. # Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a cop...
25,678
53.52017
151
py
ChineseGLUE
ChineseGLUE-master/baselines/models_pytorch/classifier_pytorch/transformers/tokenization_utils.py
# coding=utf-8 # Copyright 2018 The Open AI Team Authors and The HuggingFace Inc. team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # ...
54,979
50.431244
372
py
ChineseGLUE
ChineseGLUE-master/baselines/models_pytorch/mrc_pytorch/run_mrc.py
import argparse import collections import json import os import random import numpy as np import torch from torch import nn from torch.utils.data import TensorDataset, DataLoader from tqdm import tqdm from .preprocess.cmrc2018_evaluate import get_eval from .pytorch_modeling import BertConfig, BertForQuestionAnswering...
13,652
46.40625
117
py
ChineseGLUE
ChineseGLUE-master/baselines/models_pytorch/mrc_pytorch/pytorch_modeling.py
# coding=utf-8 # Copyright 2018 The Google AI Language Team Authors and The HugginFace Inc. team. # Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy...
56,477
45.830846
130
py
ChineseGLUE
ChineseGLUE-master/baselines/models_pytorch/mrc_pytorch/convert_tf_checkpoint_to_pytorch.py
# coding=utf-8 # Copyright 2018 The HugginFace Inc. team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable ...
5,143
40.152
105
py
ChineseGLUE
ChineseGLUE-master/baselines/models_pytorch/mrc_pytorch/tools/pytorch_optimization.py
# coding=utf-8 # Copyright 2018 The Google AI Language Team Authors and The HugginFace Inc. team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENS...
8,435
41.606061
116
py
ChineseGLUE
ChineseGLUE-master/baselines/models_pytorch/mrc_pytorch/tools/utils.py
import collections import os import re from glob import glob import tensorflow as tf import tensorflow.contrib.slim as slim import torch def check_args(args): args.setting_file = os.path.join(args.checkpoint_dir, args.setting_file) args.log_file = os.path.join(args.checkpoint_dir, args.log_file) os.maked...
4,999
33.013605
117
py
ChineseGLUE
ChineseGLUE-master/baselines/models_pytorch/mrc_pytorch/tools/file_utils.py
""" Utilities for working with the local dataset cache. This file is adapted from the AllenNLP library at https://github.com/allenai/allennlp Copyright by the AllenNLP authors. """ import json import logging import os import shutil import tempfile from functools import wraps from hashlib import sha256 from pathlib imp...
8,020
32.560669
98
py
LAAT
LAAT-master/src/training.py
from torch import optim from src.util.preprocessing import * from src.util.util import to_md5 from src.util.util import get_n_training_labels from src.data_helpers.dataloaders import TextDataset, TextDataLoader from src.trainer import Trainer from src.evaluator import Evaluator from src.args_parser import * import pi...
13,783
38.723343
114
py
LAAT
LAAT-master/src/evaluator.py
from src.data_helpers.dataloaders import * import warnings from src.data_helpers.vocab import device from src.util.util import * from tqdm import tqdm from collections import OrderedDict warnings.filterwarnings('ignore') # want to remove some warning from sklearn class Evaluator: def __init__(self, ...
4,034
37.066038
113
py
LAAT
LAAT-master/src/trainer.py
from src.evaluator import * import numpy as np import os from torch.autograd import Variable from src.models.attentions.attention_layer import * np.set_printoptions(precision=5) from tqdm import tqdm from collections import OrderedDict import shutil class Trainer: def __init__(self, model: nn.Module, ...
13,423
42.443366
120
py
LAAT
LAAT-master/src/models/cnn.py
# -*- coding: utf-8 -*- """ Word-based CNN model for text classification from the paper Kim, Yoon. "Convolutional neural networks for sentence classification." arXiv preprint arXiv:1408.5882 (2014) https://arxiv.org/abs/1408.5882 Add the support of char features learned from RNN or CNN to enrich word em...
3,884
32.491379
117
py
LAAT
LAAT-master/src/models/rnn.py
# -*- coding: utf-8 -*- """ Word-based RNN model for text classification @author: Thanh Vu <thanh.vu@csiro.au> @date created: 07/03/2019 @date last modified: 19/08/2020 """ from torch.autograd import Variable from torch.nn.utils.rnn import pack_padded_sequence, pad_packed_sequence from src.models.atten...
4,760
36.488189
114
py
LAAT
LAAT-master/src/models/tcn.py
# -*- coding: utf-8 -*- """ TCN model for text classification @author: Thanh Vu <thanh.vu@csiro.au> @date created: 07/05/2019 @date last modified: 19/08/2020 """ import torch.nn as nn from torch.nn.utils import weight_norm class Chomp1d(nn.Module): def __init__(self, chomp_size): super(Ch...
2,883
35.974359
115
py
LAAT
LAAT-master/src/models/attentions/util.py
from src.models.attentions.attention_layer import * def init_attention_layer(model): if model.args.joint_mode == "flat": if model.attention_mode is not None: model.attention = AttentionLayer(args=model.args, size=model.output_size, n_labels=model.vo...
5,075
51.329897
118
py
LAAT
LAAT-master/src/models/attentions/attention_layer.py
""" This class is to implement the attention layer which supports hard attention, self-structured attention and self attention @author: Thanh Vu <thanh.vu@csiro.au> @date created: 20/03/2019 @date last modified: 19/08/2020 """ import torch import torch.nn as nn import torch.nn.functional as F ...
5,695
40.275362
145
py
LAAT
LAAT-master/src/models/embeddings/embedding_layer.py
# -*- coding: utf-8 -*- """ This is to create the embedding layer with the support of character-based word embeddings @author: Thanh Vu <thanh.vu@csiro.au> @date created: 01/04/2019 @date last modified: 19/08/2020 """ import torch.nn as nn import torch import copy class EmbeddingLayer(nn.Module): ...
3,374
43.407895
132
py
LAAT
LAAT-master/src/util/util.py
import numpy as np from sklearn.metrics import * from sklearn.preprocessing import * import random import torch import hashlib # This is for shuffling the data and initialise the "UNKNOWN" word embedding random.seed(0) np.random.seed(0) # This is to set the random seed if needed def set_random_seed(random_seed): ...
13,048
33.612732
122
py
LAAT
LAAT-master/src/data_helpers/vocab.py
# -*- coding: utf-8 -*- """ This is to create the vocabularies which are used to convert the text data into tensor format Author: Thanh Vu <thanh.vu@csiro.au> Date created: 01/03/2019 Date last modified: 19/03/2019 """ import os import torch from collections import Counter import numpy as np from gensim...
7,978
33.842795
103
py
LAAT
LAAT-master/src/data_helpers/dataloaders.py
# -*- coding: utf-8 -*- """ This provides the functions to load the data for training and testing the model (e.g., batch) Author: Thanh Vu <thanh.vu@csiro.au> Date created: 01/03/2019 Date last modified: 19/08/2020 """ import torch from torch.utils.data import DataLoader, Dataset from src.util.preproces...
7,256
34.4
102
py
TreeBERT
TreeBERT-master/__main__.py
import argparse import copy import torch from torch.utils.data import DataLoader from dataset import BPE, TokenVocab, TreeBERTDataset from model import Decoder, Encoder, Seq2Seq from trainer import BERTTrainer def train(): parser = argparse.ArgumentParser() parser.add_argument("-td", "--train_dataset", type...
4,944
51.606383
133
py
TreeBERT
TreeBERT-master/trainer/pretrain.py
import sys import torch import torch.nn as nn from torch.optim import Adam from torch.utils.data import DataLoader from .optim_schedule import ScheduledOptim sys.path.append("..") import tqdm from model import TreeBERT, transformer class BERTTrainer: def __init__(self, transformer, alpha, vocab_size: int, ...
3,882
38.222222
141
py
TreeBERT
TreeBERT-master/dataset/utils.py
import base64 import json import os import random import socket import sys import time from urllib import request import matplotlib.pyplot as plt import matplotlib.ticker as ticker # from torchtext.data.metrics import bleu_score import torch import torch.nn as nn import tqdm def getPretrainData(str): socket.setd...
7,236
26.003731
149
py
TreeBERT
TreeBERT-master/dataset/dataset.py
import json import os import torch from torch.utils.data import Dataset from dataset import BPE class TreeBERTDataset(Dataset): def __init__(self, vocab, corpus_path, path_num, node_num, code_len, is_fine_tune=False, corpus_lines=None, max_subtoken_len=3): ...
4,323
37.607143
137
py
TreeBERT
TreeBERT-master/dataset/vocab.py
#coding=utf-8 import collections import json import os import pickle import re from tqdm import tqdm class BPE(object): def __init__(self, corpus_path, BPE_path="data/BPEObject.small", except_list=None, num_merges=5): print("Read in files") print('==========') vocab = self.get_vocab(corp...
13,962
37.786111
147
py
TreeBERT
TreeBERT-master/model/transformer.py
import random import numpy as np import torch import torch.nn as nn SEED = 1234 random.seed(SEED) np.random.seed(SEED) torch.manual_seed(SEED) torch.cuda.manual_seed(SEED) torch.backends.cudnn.deterministic = True class PathEncoder(nn.Module): def __init__(self, input_dim, no...
9,317
31.694737
140
py
TreeBERT
TreeBERT-master/model/treebert.py
import torch.nn as nn class TreeBERT(nn.Module): def __init__(self, transformer, vocab_size): super().__init__() self.transformer = transformer self.mask_lm = MaskedLanguageModel(self.transformer.hidden, vocab_size) self.node_order_prediction = NodeOrderPrediction(self.transformer.h...
999
30.25
82
py
machamp
machamp-master/predict.py
import argparse import logging import sys import torch from machamp.predictor.predict import predict_with_paths logging.basicConfig(format='%(asctime)s - %(levelname)s - %(name)s - %(message)s', level=logging.INFO, handlers=[logging.StreamHandler(sys.stdout)]) logger = logging.getLogger(__name__)...
2,751
47.280702
177
py
machamp
machamp-master/train.py
import argparse import sys import torch from machamp.model import trainer parser = argparse.ArgumentParser() parser.add_argument("--dataset_configs", nargs='+', help="Path(s) to dataset configurations (use --sequential to train on them sequentially, " "default is joint tr...
2,653
45.561404
126
py
machamp
machamp-master/scripts/misc/extract_automodel.py
import os import sys import torch from transformers import AutoTokenizer from machamp.model.machamp import MachampModel model = torch.load(sys.argv[1]) outPath = sys.argv[2] if not os.path.isdir(outPath): os.mkdir(outPath) model.mlm.save_pretrained(outPath) tokenizer = AutoTokenizer.from_pretrained(model.mlm.nam...
431
24.411765
65
py
machamp
machamp-master/machamp/predictor/predict.py
import json import logging import os from typing import List, Any, Dict import torch from torch.utils.data import DataLoader logger = logging.getLogger(__name__) from machamp.utils.lemma_edit import apply_lemma_rule from machamp.utils.myutils import prep_batch, report_metrics from machamp.data.machamp_dataset_collec...
11,503
47.745763
178
py
machamp
machamp-master/machamp/modules/allennlp/conditional_random_field.py
""" Conditional random field """ import logging from typing import List, Tuple, Union import torch logger = logging.getLogger(__name__) import machamp.modules.allennlp.util as util VITERBI_DECODING = Tuple[List[int], float] # a list of tags, and a viterbi score def allowed_transitions(constraint_type: str, label...
19,163
41.776786
121
py
machamp
machamp-master/machamp/modules/allennlp/slanted_triangular.py
# Borrowed from allennlp, to avoid having to install the whole allennlp library import logging from typing import List, Optional import torch from torch.optim.lr_scheduler import _LRScheduler logger = logging.getLogger(__name__) class SlantedTriangular(_LRScheduler): """ Implements the Slanted Triangular L...
8,889
46.037037
97
py
machamp
machamp-master/machamp/modules/allennlp/util.py
import logging import math from typing import List, Optional, Tuple, Set import torch logger = logging.getLogger(__name__) TypedStringSpan = Tuple[str, Tuple[int, int]] def viterbi_decode( tag_sequence: torch.Tensor, transition_matrix: torch.Tensor, tag_observations: Optional[List[int]] = N...
12,281
41.794425
100
py
machamp
machamp-master/machamp/modules/allennlp/bilinear_matrix_attention.py
# Borrowed from allennlp, to avoid having to install the whole allennlp library import torch from torch.nn.parameter import Parameter # linear activation class Identity: def forward(self, x: torch.Tensor) -> torch.Tensor: return x class BilinearMatrixAttention(torch.nn.Module): """ Computes atte...
3,571
40.057471
99
py
machamp
machamp-master/machamp/modules/allennlp/scalar_mix.py
# Borrowed from allennlp, to avoid having to install the whole allennlp library import logging from typing import List import torch from torch.nn import Parameter logger = logging.getLogger(__name__) class ScalarMix(torch.nn.Module): """ Computes a parameterised scalar mixture of N tensors, `mixture = gamma...
3,789
38.072165
100
py
machamp
machamp-master/machamp/metrics/las.py
import torch class LAS: def __init__(self): self.cor = 0 self.total = 0 self.str = 'las' self.metric_scores = {} def score(self, pred_heads, pred_rels, gold_heads, gold_rels): pred_rels = pred_rels.flatten() gold_rels = gold_rels.flatten() cor_rels = go...
1,006
24.175
66
py
machamp
machamp-master/machamp/metrics/pearson.py
import torch # This could better be converted to be fuly in torch, or fully in native python def get_std_scores(x): standard_score_x = [] mean_x = sum(x)/len(x) standard_deviation_x = torch.std(torch.tensor(x)) for observation in x: standard_score_x.append((observation - mean_x)/standard_deviat...
1,282
28.159091
91
py
machamp
machamp-master/machamp/metrics/f1.py
import logging import torch logger = logging.getLogger(__name__) class F1: def __init__(self, type_f1): self.tps = [] self.fps = [] self.fns = [] self.type_f1 = type_f1 self.str = 'f1_' + type_f1 self.vocabulary = [] self.metric_scores = {} def score(...
4,573
35.592
98
py
machamp
machamp-master/machamp/metrics/avg_dist.py
import torch class AvgDist: def __init__(self): self.dists = [] self.str = 'avg_dist' self.metric_scores = {} def score(self, preds, golds, vocabulary): self.dists.extend(torch.abs(preds.flatten() - golds.flatten()).tolist()) def reset(self): self.dists = [] ...
645
22.925926
80
py
machamp
machamp-master/machamp/metrics/accuracy.py
import torch class Accuracy: def __init__(self): self.cor = 0 self.total = 0 self.str = 'accuracy' self.metric_scores = {} def score(self, preds, golds, vocabulary): preds = torch.flatten(preds) golds = torch.flatten(golds) contents = torch.nonzero(gol...
870
21.921053
64
py
machamp
machamp-master/machamp/metrics/uas.py
import torch class UAS: def __init__(self): self.cor = 0 self.total = 0 self.str = 'uas' self.metric_scores = {} def score(self, pred_heads, pred_rels, gold_heads, gold_rels): pred_heads = pred_heads.flatten() gold_heads = gold_heads.flatten() cor_heads...
891
23.777778
66
py
machamp
machamp-master/machamp/metrics/multi_accuracy.py
import torch class MultiAccuracy: def __init__(self): self.cor = 0 self.total = 0 self.str = 'multi_acc' self.metric_scores = {} def score(self, preds, golds, mask=None, vocabulary=None): # Maybe this be done more efficient by using torch functions? if len(pred...
1,262
29.804878
93
py
machamp
machamp-master/machamp/readers/read_raw.py
import logging from typing import List import torch from transformers import AutoTokenizer from machamp.data.machamp_instance import MachampInstance from machamp.data.machamp_vocabulary import MachampVocabulary logger = logging.getLogger(__name__) def read_raw( dataset: str, config: dict, t...
3,312
31.80198
140
py
machamp
machamp-master/machamp/readers/read_sequence.py
import logging from typing import List import torch from transformers import AutoTokenizer from transformers.models.bert.tokenization_bert import BasicTokenizer from transformers.models.bert.tokenization_bert import BertTokenizer from transformers.models.xlm_roberta.tokenization_xlm_roberta import XLMRobertaTokenizer ...
20,799
47.484848
128
py
machamp
machamp-master/machamp/readers/read_mlm.py
import logging from typing import List import torch from transformers import AutoTokenizer from transformers import DataCollatorForLanguageModeling # or DataCollatorForWholeWordMask from machamp.data.machamp_instance import MachampInstance from machamp.data.machamp_vocabulary import MachampVocabulary logger = loggi...
5,107
37.992366
131
py
machamp
machamp-master/machamp/readers/read_classification.py
import copy import logging from typing import List import torch from transformers import AutoTokenizer from machamp.data.machamp_instance import MachampInstance from machamp.data.machamp_vocabulary import MachampVocabulary logger = logging.getLogger(__name__) def lines2data(input_file: str, skip_first_line: bool =...
8,144
39.123153
156
py
machamp
machamp-master/machamp/utils/myutils.py
import copy import json import logging import re from typing import List, Dict, Tuple, Optional, Any, Union, Iterator import _jsonnet import torch logger = logging.getLogger(__name__) from transformers import tokenization_utils from transformers import AutoTokenizer from machamp.data.machamp_instance import Machamp...
19,623
39.213115
137
py
machamp
machamp-master/machamp/utils/tok_utils.py
import logging import os from typing import List import torch from transformers import AutoTokenizer from transformers import tokenization_utils from transformers.models.bert.tokenization_bert import BasicTokenizer from machamp.utils.lemma_edit import min_edit_script logger = logging.getLogger(__name__) class Scrip...
22,378
37.584483
177
py
machamp
machamp-master/machamp/data/machamp_sampler.py
import logging import math import random from typing import Iterator, List, Tuple from torch.utils.data import Sampler from machamp.data.machamp_dataset import MachampDataset logger = logging.getLogger(__name__) class MachampBatchSampler(Sampler): def __init__(self, data_source: MachampDatas...
9,016
39.986364
130
py
machamp
machamp-master/machamp/data/machamp_dataset_collection.py
import datetime import logging from typing import Dict, Tuple, List from torch.utils.data import Dataset from transformers import AutoTokenizer from machamp.data.machamp_instance import MachampInstance from machamp.data.machamp_vocabulary import MachampVocabulary from machamp.data.machamp_dataset import MachampDatase...
6,231
38.694268
187
py
machamp
machamp-master/machamp/data/machamp_dataset.py
import datetime import logging from typing import Dict, Tuple, List from torch.utils.data import Dataset from transformers import AutoTokenizer from machamp.data.machamp_instance import MachampInstance from machamp.data.machamp_vocabulary import MachampVocabulary from machamp.readers.read_classification import read_c...
7,364
40.846591
120
py
machamp
machamp-master/machamp/data/machamp_instance.py
from typing import List, Dict, Any import torch class MachampInstance: def __init__(self, full_data: List[str], token_ids: torch.tensor, seg_ids: torch.tensor, golds: Dict[Any, torch.tensor], dataset: str, offse...
2,518
34.985714
89
py
machamp
machamp-master/machamp/model/machamp.py
import logging from typing import List, Dict import torch logger = logging.getLogger(__name__) from transformers import AutoModel, AutoTokenizer, AutoModelForMaskedLM from transformers import logging as tf_logging tf_logging.set_verbosity_error() from machamp.metrics.avg_dist import AvgDist from machamp.metrics.pe...
26,289
45.862745
135
py
machamp
machamp-master/machamp/model/seq_label_decoder.py
import torch import torch.nn.functional as F from machamp.model.machamp_decoder import MachampDecoder class MachampSeqDecoder(MachampDecoder, torch.nn.Module): def __init__( self, task: str, vocabulary, input_dim: int, device: str, loss_weig...
3,004
42.550725
120
py
machamp
machamp-master/machamp/model/classification_decoder.py
import torch import torch.nn.functional as F from machamp.model.machamp_decoder import MachampDecoder class MachampClassificationDecoder(MachampDecoder, torch.nn.Module): def __init__(self, task, vocabulary, input_dim, device, loss_weight: float = 1.0, topn: int = 1, metric: str = 'accuracy', **...
2,172
47.288889
111
py
machamp
machamp-master/machamp/model/dependency_decoder.py
## This dependency head is mainly based on the Allennlp implementation: ## https://github.com/allenai/allennlp-models/blob/main/allennlp_models/structured_prediction/models/biaffine_dependency_parser.py import copy import logging from typing import Dict, Tuple import numpy import torch import torch.nn.functional as ...
32,085
48.439137
130
py
machamp
machamp-master/machamp/model/mlm_decoder.py
import logging import torch from machamp.model.machamp_decoder import MachampDecoder logger = logging.getLogger(__name__) class MachampLMDecoder(MachampDecoder, torch.nn.Module): def __init__( self, task: str, vocabulary, input_dim: int, device: str, ...
1,508
34.093023
107
py
machamp
machamp-master/machamp/model/encoder.py
import inspect import logging import math import torch logger = logging.getLogger(__name__) from transformers import AutoModel class MachampEncoder: def __init__(self, mlm: AutoModel, max_input_length: int, end_token_id: int, start_token_id: i...
18,489
52.285303
140
py
machamp
machamp-master/machamp/model/multiclas_decoder.py
import logging import torch from machamp.model.machamp_decoder import MachampDecoder logger = logging.getLogger(__name__) class MachampMulticlasDecoder(MachampDecoder, torch.nn.Module): def __init__(self, task, vocabulary, input_dim, device, loss_weight: float = 1.0, topn: int = 1, metric: str...
2,358
42.685185
117
py
machamp
machamp-master/machamp/model/machamp_decoder.py
import logging import torch logger = logging.getLogger(__name__) from machamp.metrics.metric import Metric class MachampDecoder(torch.nn.Module): def __init__(self, task, vocabulary, loss_weight: float = 1.0, metric: str = 'avg_dist', device: str = 'cpu', **kwargs): super().__init__() self.task...
1,712
37.066667
137
py
machamp
machamp-master/machamp/model/multiseq_decoder.py
import logging import torch from machamp.model.machamp_decoder import MachampDecoder logger = logging.getLogger(__name__) class MachampMultiseqDecoder(MachampDecoder, torch.nn.Module): def __init__( self, task: str, vocabulary, input_dim: int, device: ...
3,567
42.512195
124
py
machamp
machamp-master/machamp/model/callback.py
import datetime import json import logging import os import torch logger = logging.getLogger(__name__) from machamp.model.machamp import MachampModel class Callback: def __init__(self, serialization_dir, num_epochs, keep_best_n: int = 1): """ Class that keeps track of performance of models over...
14,576
45.721154
127
py
machamp
machamp-master/machamp/model/regression_decoder.py
import torch from machamp.model.machamp_decoder import MachampDecoder class MachampRegressionDecoder(MachampDecoder, torch.nn.Module): def __init__(self, task, vocabulary, input_dim, device, loss_weight: float = 1.0, topn: int = 1, metric: str = 'avg_dist', **kwargs): super().__init__(ta...
1,416
40.676471
118
py
machamp
machamp-master/machamp/model/crf_label_decoder.py
import logging from typing import cast, List import torch import torch.nn.functional as F logger = logging.getLogger(__name__) from machamp.model.machamp_decoder import MachampDecoder from machamp.modules.allennlp.conditional_random_field import ConditionalRandomField, allowed_transitions class MachampCRFDecoder(M...
4,673
41.490909
120
py
machamp
machamp-master/machamp/model/trainer.py
import datetime import json import logging import os import random import sys from typing import List import torch import transformers from torch.utils.data import DataLoader from tqdm import tqdm from machamp.utils import myutils from machamp.model.machamp import MachampModel from machamp.model.callback import Callb...
14,703
49.356164
158
py
osyris
osyris-main/docs/conf.py
# SPDX-License-Identifier: BSD-3-Clause # Copyright (c) 2022 Osyris contributors (https://github.com/osyris-project/osyris) # Configuration file for the Sphinx documentation builder. # # This file only contains a selection of the most common options. For a full # list see the documentation: # http://www.sphinx-doc.org...
2,855
33
85
py
bla
bla-main/experiment.py
# This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # This program is distributed in the hope that it will be useful, # but...
14,086
35.306701
112
py
Bella
Bella-master/bella/word_vectors.py
''' Contains classes that train and/or load semantic vectors. All classes are sub classes of WordVectors Classes: 1. WordVectors - Base class of all classes within this module. Ensures consistent API for all word vectors classes. 2. GensimVectors - Creates `Word2Vec <https://arxiv.org/pdf/1301.3781.pdf>`_ and `FastTe...
42,796
44.432059
101
py
Bella
Bella-master/bella/models/base.py
''' Module contains all of the main base classes for the machine learning models these are grouped into 3 categories; 1. Mixin, 2. Abstract, and 3. Concrete. Mixin classes - This is a function based class that contains functions that do not rely on the type of model and are useful for all: 1. :py:class:`bella.models...
56,010
38.837127
89
py
Bella
Bella-master/bella/models/tdlstm.py
''' Module contains all of the classes that represent Machine Learning models that are within `Tang et al. 2016 paper \ <https://aclanthology.info/papers/C16-1311/c16-1311>`_: 1. :py:class:`bella.models.tdlstm.LSTM` -- LSTM model. 2. :py:class:`bella.models.tdlstm.TDLSTM` -- TDLSTM model. 3. :py:class:`bella.models.td...
39,413
45.699052
81
py
Bella
Bella-master/docs/conf.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # # Bella documentation build configuration file, created by # sphinx-quickstart on Thu Jun 7 12:24:24 2018. # # 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 # auto...
5,732
29.657754
83
py
Large-Scale-OT
Large-Scale-OT-master/simple.py
from typing import Union import numpy as np import torch import torch.nn as nn from torch.distributions import MultivariateNormal from torch.nn import Parameter from torch.optim import Adam, SGD def l2_distance(x: torch.Tensor, y: torch.Tensor) \ -> torch.Tensor: """Compute the Gram matrix holding all ||...
9,747
32.156463
77
py
Large-Scale-OT
Large-Scale-OT-master/StochasticOTClasses/StochasticOTSemiDiscrete.py
import numpy as np import time import torch import torch.nn as nn import torch.nn.functional as func from StochasticOT import PyTorchStochasticOT class PyTorchStochasticSemiDiscreteOT(PyTorchStochasticOT): def __init__(self, xt=None, wt=None, source_dual_variable_NN=None, reg_type='entropy', reg_val=0.1, device...
7,375
36.065327
178
py
Large-Scale-OT
Large-Scale-OT-master/StochasticOTClasses/StochasticOTDiscrete.py
import numpy as np import time import torch import torch.nn as nn import torch.nn.functional as func from StochasticOT import PyTorchStochasticOT class PyTorchStochasticDiscreteOT(PyTorchStochasticOT): def __init__(self, xs=None, ws=None, xt=None, wt=None, reg_type='entropy', reg_val=0.1, device_type='cpu', dev...
6,363
34.752809
157
py
Large-Scale-OT
Large-Scale-OT-master/StochasticOTClasses/StochasticOT.py
import numpy as np import time import torch import torch.nn as nn import torch.nn.functional as func class PyTorchStochasticOT: def __init__(self, reg_type='entropy', reg_val=0.1, device_type='cpu', device_index=0): self.reg_type = reg_type self.reg_val = reg_val self.dtype = torch.floa...
2,721
38.449275
181
py
Large-Scale-OT
Large-Scale-OT-master/toyXps/pytorch_semi_discrete_test.py
#%% 2-dimensional test script for the computation of regularized OT between a Gaussian and a discrete data set (semi-discrete OT) import numpy as np import matplotlib.pylab as pl import torch from StochasticOTClasses.StochasticOTSemiDiscrete import PyTorchStochasticSemiDiscreteOT reg_type = 'l2' reg_val = 0.005 devic...
2,190
36.135593
182
py
NTIRE2021-IQA-MACS-Pytorch
NTIRE2021-IQA-MACS-Pytorch-main/main.py
# PyTorch import torch from torch.utils.data import Dataset, DataLoader from torch.autograd import Variable import torchvision.transforms as tr import torch.nn.functional as F from torch.nn import Sequential # Models from unet import Unet from siamunet_conc import SiamUnet_conc from SiamUnet_conc import SiamUnet_conc f...
19,546
34.734918
173
py
NTIRE2021-IQA-MACS-Pytorch
NTIRE2021-IQA-MACS-Pytorch-main/siamunet_conc.py
import torch import torch.nn as nn import torch.nn.functional as F from torch.nn.modules.padding import ReplicationPad2d class SiamUnet_conc(nn.Module): """SiamUnet_conc segmentation network.""" def __init__(self, input_nbr, label_nbr): super(SiamUnet_conc, self).__init__() self.input_nbr = ...
7,752
40.459893
105
py
NTIRE2021-IQA-MACS-Pytorch
NTIRE2021-IQA-MACS-Pytorch-main/submission.py
import glob import os import numpy as np from skimage import io import random from tqdm import tqdm from torch.autograd import Variable from siamunet_diff import SiamUnet_diff from siamunet_conc import SiamUnet_conc from checkpoint.cinavad_sever.siamunet_conc_extrahead import SiamUnet_conc import torch from img_ensambl...
3,037
36.04878
179
py
NTIRE2021-IQA-MACS-Pytorch
NTIRE2021-IQA-MACS-Pytorch-main/siamunet_conc_extrahead.py
import torch import torch.nn as nn import torch.nn.functional as F from torch.nn.modules.padding import ReplicationPad2d class SiamUnet_conc(nn.Module): """SiamUnet_conc segmentation network.""" def __init__(self, input_nbr, label_nbr): super(SiamUnet_conc, self).__init__() self.input_nbr = ...
8,057
40.751295
105
py
NTIRE2021-IQA-MACS-Pytorch
NTIRE2021-IQA-MACS-Pytorch-main/img_ensamble.py
import numpy as np import torch device = "cuda" def reshape_for_torch(I): """Transpose image for PyTorch coordinates.""" # out = np.swapaxes(I,1,2) # out = np.swapaxes(out,0,1) # out = out[np.newaxis,:] out = I.transpose((2, 0, 1)) out = np.expand_dims(out, axis=0) return torc...
1,822
26.621212
84
py
NTIRE2021-IQA-MACS-Pytorch
NTIRE2021-IQA-MACS-Pytorch-main/siamunet_diff.py
# Rodrigo Caye Daudt # https://rcdaudt.github.io/ # Daudt, R. C., Le Saux, B., & Boulch, A. "Fully convolutional siamese networks for change detection". In 2018 25th IEEE International Conference on Image Processing (ICIP) (pp. 4063-4067). IEEE. import torch import torch.nn as nn import torch.nn.functional as F from t...
7,814
42.176796
195
py
NTIRE2021-IQA-MACS-Pytorch
NTIRE2021-IQA-MACS-Pytorch-main/accloss.py
import torch def m_pearsonr(output, target): x = output y = target vx = x - torch.mean(x) vy = y - torch.mean(y) pr = torch.sum(vx * vy) / (torch.sqrt(torch.sum(vx ** 2)) * torch.sqrt(torch.sum(vy ** 2))) return pr def accloss(output, target): pr = m_pearsonr(output, target) retur...
449
17
95
py
NTIRE2021-IQA-MACS-Pytorch
NTIRE2021-IQA-MACS-Pytorch-main/fresunet.py
import torch import torch.nn as nn import torch.nn.functional as F from torch.nn.modules.padding import ReplicationPad2d def conv3x3(in_planes, out_planes, stride=1): "3x3 convolution with padding" return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride, padding=1) class BasicBlock_ss(nn.Module)...
6,150
30.22335
118
py
NTIRE2021-IQA-MACS-Pytorch
NTIRE2021-IQA-MACS-Pytorch-main/sodeep_master/sodeep.py
""" ****************** COPYRIGHT AND CONFIDENTIALITY INFORMATION ****************** Copyright (c) 2019 [Thomson Licensing] All Rights Reserved This program contains proprietary information which is a trade secret/business \ secret of [Thomson Licensing] and is protected, even if unpublished, under \ applicable Copyrigh...
4,792
34.768657
131
py
NTIRE2021-IQA-MACS-Pytorch
NTIRE2021-IQA-MACS-Pytorch-main/sodeep_master/utils.py
""" ****************** COPYRIGHT AND CONFIDENTIALITY INFORMATION ****************** Copyright (c) 2019 [Thomson Licensing] All Rights Reserved This program contains proprietary information which is a trade secret/business \ secret of [Thomson Licensing] and is protected, even if unpublished, under \ applicable Copyrigh...
2,917
32.159091
101
py
NTIRE2021-IQA-MACS-Pytorch
NTIRE2021-IQA-MACS-Pytorch-main/sodeep_master/model.py
""" ****************** COPYRIGHT AND CONFIDENTIALITY INFORMATION ****************** Copyright (c) 2019 [Thomson Licensing] All Rights Reserved This program contains proprietary information which is a trade secret/business \ secret of [Thomson Licensing] and is protected, even if unpublished, under \ applicable Copyrigh...
9,461
29.621359
124
py
NTIRE2021-IQA-MACS-Pytorch
NTIRE2021-IQA-MACS-Pytorch-main/sodeep_master/dataset.py
""" ****************** COPYRIGHT AND CONFIDENTIALITY INFORMATION ****************** Copyright (c) 2019 [Thomson Licensing] All Rights Reserved This program contains proprietary information which is a trade secret/business \ secret of [Thomson Licensing] and is protected, even if unpublished, under \ applicable Copyrigh...
3,835
34.192661
103
py
NTIRE2021-IQA-MACS-Pytorch
NTIRE2021-IQA-MACS-Pytorch-main/sodeep_master/train.py
""" ****************** COPYRIGHT AND CONFIDENTIALITY INFORMATION ****************** Copyright (c) 2019 [Thomson Licensing] All Rights Reserved This program contains proprietary information which is a trade secret/business \ secret of [Thomson Licensing] and is protected, even if unpublished, under \ applicable Copyrigh...
7,607
38.015385
117
py
fgivenx
fgivenx-master/docs/source/conf.py
# -*- coding: utf-8 -*- # # Configuration file for the Sphinx documentation builder. # # This file does only contain a selection of the most common options. For a # full list see the documentation: # http://www.sphinx-doc.org/en/master/config # -- Path setup ------------------------------------------------------------...
6,325
28.699531
78
py
CuPL
CuPL-main/imagenetdataset.py
import pathlib import tarfile import requests import shutil from collections import defaultdict from PIL import Image from tqdm import tqdm from torch.utils.data import Dataset, DataLoader from torchvision.datasets import ImageFolder import os from imagenet_classnames.sense_to_idx import sense from imagenet_classnames...
1,553
25.338983
65
py
CuPL
CuPL-main/classify_imagenet.py
import numpy as np import torch import clip from pkg_resources import packaging from imagenet_prompts.standard_image_prompts import imagenet_templates import pdb from collections import defaultdict from imagenetdataset import ImagenetDataset from PIL import Image import PIL import json from tqdm import tqdm PATH_TO_IM...
3,807
30.213115
126
py
CuPL
CuPL-main/imagenet_classnames/sense_to_idx.py
sense = {0: {'id': '01440764-n', 'label': 'tench, Tinca tinca', 'uri': 'http://wordnet-rdf.princeton.edu/wn30/01440764-n'}, 1: {'id': '01443537-n', 'label': 'goldfish, Carassius auratus', 'uri': 'http://wordnet-rdf.princeton.edu/wn30/01443537-n'}, 2: {'id': '01484850-n', 'label': 'great white...
134,353
43.769743
140
py
CuPL
CuPL-main/imagenet_classnames/imagenet_classes.py
imagenet_classes = ["tench", "goldfish", "great white shark", "tiger shark", "hammerhead shark", "electric ray", "stingray", "rooster", "hen", "ostrich", "brambling", "goldfinch", "house finch", "junco", "indigo bunting", "American robin", "bulbul", "jay", "magpie", "chickadee", "American dipper", "kite (bird of prey)"...
14,834
7,416.5
14,833
py