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 |
|---|---|---|---|---|---|---|
UDAStrongBaseline | UDAStrongBaseline-master/UDAsbs/utils/data/preprocessor.py | from __future__ import absolute_import
import os
import os.path as osp
from torch.utils.data import DataLoader, Dataset
import numpy as np
import random
import math
import torch
from PIL import Image
class Preprocessor(Dataset):
def __init__(self, dataset, root=None, transform=None, mutual=False):
super(Pr... | 4,805 | 30.827815 | 111 | py |
UDAStrongBaseline | UDAStrongBaseline-master/UDAsbs/utils/data/functional_our.py | # encoding: utf-8
"""
@author: liaoxingyu
@contact: sherlockliao01@gmail.com
"""
import numpy as np
import torch
from PIL import Image, ImageOps, ImageEnhance
def to_tensor(pic):
"""Convert a ``PIL Image`` or ``numpy.ndarray`` to tensor.
See ``ToTensor`` for more details.
Args:
pic (PIL Image ... | 5,912 | 30.121053 | 79 | py |
UDAStrongBaseline | UDAStrongBaseline-master/UDAsbs/utils/data/transforms.py | from __future__ import absolute_import
__all__ = ['ToTensor', 'RandomErasing', 'RandomPatch', 'AugMix', 'ColorChange', ]
from torchvision.transforms import *
from PIL import Image
import random
import math
import numpy as np
import cv2
from collections import deque
from .functional_our import to_tensor, augmentation... | 10,430 | 35.344948 | 96 | py |
UDAStrongBaseline | UDAStrongBaseline-master/UDAsbs/evaluation_metrics/classification.py | from __future__ import absolute_import
import torch
from ..utils import to_torch
def accuracy(output, target, topk=(1,)):
with torch.no_grad():
output, target = to_torch(output), to_torch(target)
maxk = max(topk)
batch_size = target.size(0)
_, pred = output.topk(maxk, 1, True, Tr... | 604 | 26.5 | 77 | py |
UDAStrongBaseline | UDAStrongBaseline-master/UDAsbs/evaluation_metrics/__init__.py | from __future__ import absolute_import
from .classification import accuracy
from .ranking import cmc, mean_ap
__all__ = [
'accuracy',
'cmc',
'mean_ap'
]
| 167 | 14.272727 | 38 | py |
UDAStrongBaseline | UDAStrongBaseline-master/UDAsbs/evaluation_metrics/ranking.py | from __future__ import absolute_import
from collections import defaultdict
import numpy as np
from sklearn.metrics import average_precision_score
from ..utils import to_numpy
def _unique_sample(ids_dict, num):
mask = np.zeros(num, dtype=np.bool)
for _, indices in ids_dict.items():
i = np.random.choi... | 4,126 | 34.577586 | 72 | py |
yago3 | yago3-master/scripts/dumps/docopt.py | """Pythonic command-line interface parser that will make you smile.
* http://docopt.org
* Repository and issue-tracker: https://github.com/docopt/docopt
* Licensed under terms of MIT license (see LICENSE-MIT)
* Copyright (c) 2013 Vladimir Keleshev, vladimir@keleshev.com
"""
import sys
import re
__all__ = ['doco... | 19,946 | 33.391379 | 79 | py |
yago3 | yago3-master/scripts/dumps/downloadDumps.py | #!/usr/bin/env python
# encoding: utf-8
"""
Downloads Wikipedia, Wikidata and commonswiki dumps for the specified languages unless they are explicitly specified in the YAGO configuration file via the properties named "wikipedias", "wikidata" or "commons_wiki". For all dumps, the most recent version is downloaded unles... | 17,912 | 32.357542 | 301 | py |
RefNet | RefNet-master/inference.py | from __future__ import print_function
import os
import tensorflow as tf
import greed_search
import data
import util
import evaluate
import json
import glob
import shutil
FLAGS = tf.app.flags.FLAGS
class Inference:
"""greed search decoder."""
def __init__(self, model, batcher, vocab, ckpt_path):
self.... | 7,162 | 48.743056 | 262 | py |
RefNet | RefNet-master/greed_search.py | import tensorflow as tf
import data
FLAGS = tf.app.flags.FLAGS
class Hypothesis:
"""Class to represent a hypothesis during beam search. Holds all the information needed for the hypothesis."""
def __init__(self, tokens, probs, state, attn_dists, switch_ref_probs, switch_gen_probs, switch_gen_pred_probs, swit... | 4,122 | 46.390805 | 296 | py |
RefNet | RefNet-master/batcher.py | """This file contains code to process data into batches"""
import queue
from random import shuffle
from threading import Thread
import time
import numpy as np
from collections import namedtuple
import tensorflow as tf
import data
class Example:
"""Class representing a train/val/test example for response generatio... | 22,095 | 50.990588 | 185 | py |
RefNet | RefNet-master/evaluate.py | import sys
import glob
import json
import os
import time
from metrics import rouge, bleu, f1
def rounder(num):
return round(num, 2)
def bleu_max_over_ground_truths(prediction, ground_truths):
scores_for_ground_truths = []
for ground_truth in ground_truths:
score = cal_bleu([prediction], [ground_... | 6,732 | 38.145349 | 302 | py |
RefNet | RefNet-master/model.py | import time
import numpy as np
import tensorflow as tf
from hybrid_decoder import hybrid_decoder
import util
FLAGS = tf.app.flags.FLAGS
class Model:
def __init__(self, hps, vocab):
self._hps = hps
self._vocab = vocab
def _add_placeholders(self):
"""Add placeholders to the graph. Thes... | 32,058 | 68.092672 | 223 | py |
RefNet | RefNet-master/data.py | import glob
import random
import struct
import copy
from tensorflow.core.example import example_pb2
PAD_TOKEN = '[PAD]' # This has a vocab id, which is used to pad the encoder input, decoder input and target sequence
UNKNOWN_TOKEN = '[UNK]' # This has a vocab id, which is used to represent out-of-vocabulary words
STAR... | 10,802 | 36.380623 | 213 | py |
RefNet | RefNet-master/hybrid_decoder.py | import tensorflow as tf
import util
def hybrid_decoder(decoder_inputs, initial_state, encoder_states, enc_padding_mask, query_states, que_padding_mask, cell, initial_state_attention=False):
with tf.variable_scope("attention_decoder"):
batch_size = encoder_states.get_shape()[0].value # batch_size if this ... | 8,361 | 55.884354 | 158 | py |
RefNet | RefNet-master/run.py | import time
import os
import tensorflow as tf
import numpy as np
from collections import namedtuple
from data import Vocab
from batcher import Batcher
from model import Model
from inference import Inference
import util
import yaml
import json
import time
FLAGS = tf.app.flags.FLAGS
tf.app.flags.DEFINE_string('config_f... | 10,254 | 48.302885 | 276 | py |
RefNet | RefNet-master/util.py | import tensorflow as tf
import time
import os
FLAGS = tf.app.flags.FLAGS
def get_config():
"""Returns config for tf.session"""
config = tf.ConfigProto(allow_soft_placement=True)
config.gpu_options.allow_growth = True
return config
def mask_softmax(seq_mask, scores):
seq_mask = tf.cast(seq_mask,... | 3,441 | 34.122449 | 103 | py |
RefNet | RefNet-master/metrics/f1.py | """ Official evaluation script for v1.1 of the SQuAD dataset. """
from __future__ import print_function
from collections import Counter
import string
import re
import argparse
import json
import sys
def normalize_answer(s):
"""Lower text and remove punctuation, articles and extra whitespace."""
def remove_art... | 2,259 | 31.285714 | 117 | py |
RefNet | RefNet-master/metrics/bleu.py | # -*- coding: utf-8 -*-
# Copyright 2017 Google Inc.
#
# 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 law ... | 3,320 | 32.887755 | 80 | py |
RefNet | RefNet-master/metrics/rouge.py | # -*- coding: utf-8 -*-
# Copyright 2017 Google Inc.
#
# 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 law ... | 10,971 | 29.060274 | 80 | py |
RefNet | RefNet-master/data/preprocress.py | import os
import json
import struct
import collections
from tensorflow.core.example import example_pb2
import re
import spacy
nlp = spacy.load('en', disable=['tagger', 'ner'], vectors=False)
print('Spacy loaded')
def get_tokens(doc):
doc = nlp(doc)
new_tokens = []
for k in doc:
new_tokens.append(... | 11,726 | 40.438163 | 154 | py |
RefNet | RefNet-master/data/preprocress_multi_ref.py | import os
import json
import struct
import collections
import re
import spacy
nlp = spacy.load('en', disable=['tagger', 'ner'], vectors=False)
print('Spacy loaded')
def get_tokens(doc): # 分词用
doc = nlp(doc)
new_tokens = []
for k in doc:
new_tokens.append(k.text)
return new_tokens
def proce... | 1,227 | 24.061224 | 90 | py |
coling2016-pcrf-seq2seq | coling2016-pcrf-seq2seq-master/src/makeAlign-seg_complex.py | #! /usr/bin/python
import sys
try:
WINDOW = int(sys.argv[1])
MY_N = int(sys.argv[2])
except IndexError:
WINDOW = 6
MY_N = 6
def createNgramTemplate(integer,mystring,n,window,stringIndex):
counter = 0
m = len(mystring)
features = []
joinSym=""
for i in xrange(-window,window-n+2,1):
#print "s%d:"... | 2,231 | 27.987013 | 138 | py |
coling2016-pcrf-seq2seq | coling2016-pcrf-seq2seq-master/src/extractStrings.py | #! /usr/bin/python
import sys
chars = []
preds = []
EMPTY="EMPTY"
for line in sys.stdin:
line = line.strip()
if line=="":
print "%s\t%s"%(" ".join(chars)," ".join(preds))
chars = []
preds = []
else:
x = line.split("\t")
char = x[1]
pred = x[5]
#if pred[-1]... | 448 | 17.708333 | 56 | py |
coling2016-pcrf-seq2seq | coling2016-pcrf-seq2seq-master/src/removeLast.py | #! /usr/bin/python
import sys
for line in sys.stdin:
line = line.strip()
a,b = line.split()
print "%s\t%s"%(a[:-1],b[:-1])
| 131 | 13.666667 | 32 | py |
coling2016-pcrf-seq2seq | coling2016-pcrf-seq2seq-master/src/makeSeg_complex.py | #! /usr/bin/python
import sys
try:
WINDOW = int(sys.argv[1])
MY_N = int(sys.argv[2])
except IndexError:
WINDOW = 6
MY_N = 6
def createNgramTemplate(integer,mystring,n,window,stringIndex):
counter = 0
m = len(mystring)
features = []
for i in xrange(-window,window-n+2,1):
#print "s%d:"%(counter) +... | 1,770 | 24.3 | 126 | py |
articles | articles-master/Classifying Processes Instances Using Recurrent Neural Networks/testframework/main.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Dec 25 11:59:43 2017
Test framework sources used to perform the tests required by paper: "Classifying Processes Instances Using Recurrent Neural Networks"
by Markku Hinkka, Teemu Lehto, Keijo Heljanko and Alexander Jung
"""
import lasagne
from lasagne.... | 7,759 | 44.647059 | 192 | py |
articles | articles-master/Classifying Processes Instances Using Recurrent Neural Networks/testframework/utils.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Dec 25 11:59:43 2017
Test framework sources used to perform the tests required by paper: "Classifying Processes Instances Using Recurrent Neural Networks"
by Markku Hinkka, Teemu Lehto, Keijo Heljanko and Alexander Jung
"""
import csv
import numpy as n... | 9,257 | 42.261682 | 570 | py |
articles | articles-master/Classifying Processes Instances Using Recurrent Neural Networks/testframework/model.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Dec 25 11:59:43 2017
Test framework sources used to perform the tests required by paper: "Classifying Processes Instances Using Recurrent Neural Networks"
by Markku Hinkka, Teemu Lehto, Keijo Heljanko and Alexander Jung
"""
import lasagne
from lasagne.... | 26,945 | 49.745763 | 221 | py |
articles | articles-master/Exploiting Event Log Event Attributes in RNN Based Prediction/src/main.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Dec 25 11:59:43 2017
Test framework sources used to perform the tests required by paper:
"Exploiting Event Log Event Attributes in RNN Based Prediction"
by Markku Hinkka, Teemu Lehto and Keijo Heljanko
"""
import sys
import os
import numpy as np
import... | 17,910 | 39.522624 | 137 | py |
articles | articles-master/Exploiting Event Log Event Attributes in RNN Based Prediction/src/eventlog.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Dec 25 11:59:43 2017
Test framework sources used to perform the tests required by paper:
"Exploiting Event Log Event Attributes in RNN Based Prediction"
by Markku Hinkka, Teemu Lehto and Keijo Heljanko
"""
import sys
import numpy as np
import json
impo... | 17,464 | 44.839895 | 208 | py |
articles | articles-master/Exploiting Event Log Event Attributes in RNN Based Prediction/src/cluster.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Dec 25 11:59:43 2017
Test framework sources used to perform the tests required by paper:
"Exploiting Event Log Event Attributes in RNN Based Prediction"
by Markku Hinkka, Teemu Lehto and Keijo Heljanko
"""
# pip install pyclustering
# conda install -c ... | 28,365 | 41.400598 | 352 | py |
articles | articles-master/Exploiting Event Log Event Attributes in RNN Based Prediction/src/my_utils.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Dec 25 11:59:43 2017
Test framework sources used to perform the tests required by paper:
"Exploiting Event Log Event Attributes in RNN Based Prediction"
by Markku Hinkka, Teemu Lehto and Keijo Heljanko
"""
import csv
import numpy as np
import time
imp... | 10,820 | 49.097222 | 1,243 | py |
articles | articles-master/Exploiting Event Log Event Attributes in RNN Based Prediction/src/bucket.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Dec 25 11:59:43 2017
Test framework sources used to perform the tests required by paper:
"Exploiting Event Log Event Attributes in RNN Based Prediction"
by Markku Hinkka, Teemu Lehto and Keijo Heljanko
"""
import sys
import lasagne
from lasagne.layers... | 8,115 | 52.394737 | 220 | py |
articles | articles-master/Exploiting Event Log Event Attributes in RNN Based Prediction/src/model.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Dec 25 11:59:43 2017
Test framework sources used to perform the tests required by paper:
"Exploiting Event Log Event Attributes in RNN Based Prediction"
by Markku Hinkka, Teemu Lehto and Keijo Heljanko
"""
import sys
import lasagne
from lasagne.layers... | 49,689 | 54.272525 | 310 | py |
articles | articles-master/Exploiting Event Log Event Attributes in RNN Based Prediction/src/modelcluster.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Dec 25 11:59:43 2017
Test framework sources used to perform the tests required by paper:
"Exploiting Event Log Event Attributes in RNN Based Prediction"
by Markku Hinkka, Teemu Lehto and Keijo Heljanko
"""
import sys
import lasagne
from lasagne.layers... | 15,958 | 46.497024 | 240 | py |
GraB | GraB-main/setup.py | import setuptools
with open("README.md", "r", encoding="utf-8") as fh:
long_description = fh.read()
setuptools.setup(
name="orderedsampler",
version="0.0.1",
author="Yucheng Lu",
author_email="yl2967@cornell.edu",
description="pytorch-based OrderedSampler that supports example ordering",
l... | 838 | 31.269231 | 78 | py |
GraB | GraB-main/neurips22/examples/nlp/BertGlue/train_bert_glue.py | # coding=utf-8
# Copyright 2021 The HuggingFace Inc. team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless r... | 26,114 | 42.236755 | 127 | py |
GraB | GraB-main/neurips22/examples/nlp/word_language_model/main.py | # coding: utf-8
import argparse
import math
import os
import torch
import torch.nn as nn
import data
import model
import random
import tqdm
import time
from contextlib import contextmanager
from tensorboardX import SummaryWriter
from constants import _STALE_GRAD_SORT_, \
_RANDOM_RESHUFFLING_, \
... | 17,784 | 39.237557 | 125 | py |
GraB | GraB-main/neurips22/examples/nlp/word_language_model/constants.py | _RANDOM_RESHUFFLING_ = 'random_reshuffling'
_SHUFFLE_ONCE_ = 'shuffle_once'
_ZEROTH_ORDER_SORT_ = 'zeroth_order_greedy_sort'
_STALE_GRAD_SORT_ = 'stale_grad_greedy_sort'
_FRESH_GRAD_SORT_ = 'fresh_grad_greedy_sort'
_DM_SORT_ = 'dm'
_FLIPFLOP_SORT_ = 'flipflop' | 260 | 36.285714 | 48 | py |
GraB | GraB-main/neurips22/examples/nlp/word_language_model/generate.py | ###############################################################################
# Language Modeling on Wikitext-2
#
# This file generates new sentences sampled from the language model
#
###############################################################################
import argparse
import torch
import data
parser = ... | 3,080 | 38 | 89 | py |
GraB | GraB-main/neurips22/examples/nlp/word_language_model/model.py | import math
import torch
import torch.nn as nn
import torch.nn.functional as F
class RNNModel(nn.Module):
"""Container module with an encoder, a recurrent module, and a decoder."""
def __init__(self, rnn_type, ntoken, ninp, nhid, nlayers, dropout=0.5, tie_weights=False):
super(RNNModel, self).__init__... | 6,353 | 41.07947 | 110 | py |
GraB | GraB-main/neurips22/examples/nlp/word_language_model/data.py | import os
from io import open
import torch
class Dictionary(object):
def __init__(self):
self.word2idx = {}
self.idx2word = []
def add_word(self, word):
if word not in self.word2idx:
self.idx2word.append(word)
self.word2idx[word] = len(self.idx2word) - 1
... | 1,449 | 28.591837 | 65 | py |
GraB | GraB-main/neurips22/examples/vision/arguments.py | import argparse
def get_args():
parser = argparse.ArgumentParser(description='Experimental code for the QMC paper')
parser.add_argument('--model',
metavar='ARCH',
default='resnet20',
help='model to use (lenet, resnetxx)')
parser.... | 6,078 | 38.219355 | 165 | py |
GraB | GraB-main/neurips22/examples/vision/constants.py | ##############################
# datasets
##############################
_MNIST_ = 'mnist'
_CIFAR10_ = 'cifar10'
_CIFAR100_ = 'cifar100'
_IMAGENET_ = 'imagenet'
##############################
# models
##############################
_LENET_ = 'lenet'
_RESNET_ = 'resnet'
_RESNET20_ = 'resnet20'
_RESNET18_ = 'resnet18'
... | 731 | 23.4 | 48 | py |
GraB | GraB-main/neurips22/examples/vision/utils.py | import os
import torch
import time
import copy
import pickle
import logging
import lmdb
from contextlib import contextmanager
from io import StringIO
from constants import _STALE_GRAD_SORT_, \
_FRESH_GRAD_SORT_, \
_DM_SORT_, \
_MNIST_, \
_F... | 13,812 | 34.058376 | 113 | py |
GraB | GraB-main/neurips22/examples/vision/visionmodel.py | import torch
from constants import _MNIST_, _SQUEEZENET_
def accuracy(output, target, topk=(1,)):
"""Computes the precision@k for the specified values of k"""
maxk = max(topk)
batch_size = target.size(0)
_, pred = output.topk(maxk, 1, True, True)
pred = pred.t()
correct = pred.eq(target.view(1... | 1,312 | 26.93617 | 64 | py |
GraB | GraB-main/neurips22/examples/vision/train_logreg_mnist.py | import os
import random
import torch
import logging
import torchvision
import torchvision.datasets as datasets
from tensorboardX import SummaryWriter
import torchvision.transforms as transforms
from visionmodel import VisionModel
from arguments import get_args
from utils import train, validate, Timer, build_task_name
f... | 6,925 | 41.231707 | 146 | py |
GraB | GraB-main/neurips22/examples/vision/train_lenet_cifar.py | import os
import random
import torch
import logging
import torchvision
import torchvision.datasets as datasets
from tensorboardX import SummaryWriter
import torchvision.transforms as transforms
from visionmodel import VisionModel
from arguments import get_args
from utils import train, validate, Timer, build_task_name
f... | 7,986 | 41.71123 | 146 | py |
GraB | GraB-main/neurips22/examples/vision/models/resnet.py | '''
Properly implemented ResNet-s for CIFAR10 as described in paper [1].
The implementation and structure of this file is hugely influenced by [2]
which is implemented for ImageNet and doesn't have option A for identity.
Moreover, most of the implementations on the web is copy-paste from
torchvision's resnet and has w... | 5,001 | 30.459119 | 120 | py |
GraB | GraB-main/neurips22/examples/vision/models/lenet.py | # -*- coding: utf-8 -*-
from collections import OrderedDict
import torch.nn as nn
__all__ = ["lenet"]
class LeNet(nn.Module):
"""
Input - 3x32x32
C1 - 6@28x28 (5x5 kernel)
tanh
S2 - 6@14x14 (2x2 kernel, stride 2) Subsampling
C3 - 16@10x10 (5x5 kernel)
tanh
S4 - 16@5x5 (2x2 kernel, st... | 2,480 | 25.677419 | 83 | py |
GraB | GraB-main/neurips22/examples/vision/models/__init__.py | from .resnet import *
from .lenet import * | 42 | 20.5 | 21 | py |
GraB | GraB-main/neurips22/src/dmsort/algo.py | import torch
import copy
import random
from sklearn import random_projection
from .utils import flatten_grad
class Sort:
def sort(self, orders):
raise NotImplementedError
class StaleGradGreedySort(Sort):
"""
Implementation of the algorithm that greedily sort the examples using staled gradients,
... | 6,539 | 38.39759 | 113 | py |
GraB | GraB-main/neurips22/src/dmsort/utils.py | import torch
from sklearn import random_projection
def random_proj(data):
rp = random_projection.SparseRandomProjection(random_state=1)
return torch.from_numpy(rp.fit_transform(data))
def compute_avg_grad_error(args,
model,
train_batches,
... | 1,844 | 33.166667 | 91 | py |
GraB | GraB-main/neurips22/src/dmsort/__init__.py | from .algo import *
from .utils import * | 40 | 19.5 | 20 | py |
GraB | GraB-main/examples/train_logistic_regression.py | import random
import torch
import torchvision
from torch.nn import CrossEntropyLoss, Linear
from orderedsampler import OrderedSampler
from tensorboardX import SummaryWriter
def accuracy(output, target, topk=(1,)):
"""Computes the precision@k for the specified values of k"""
maxk = max(topk)
batch_size = ta... | 4,204 | 31.346154 | 121 | py |
GraB | GraB-main/src/orderedsampler/utils.py | from typing import List
class IndicesTracker:
def __init__(self) -> None:
self.curr_indices = []
def _is_empty(self):
return self.curr_indices == []
def reset(self) -> None:
self.curr_indices = []
def get_indices(self) -> List[int]:
indices = self.curr_indices... | 579 | 22.2 | 49 | py |
GraB | GraB-main/src/orderedsampler/__init__.py | from absl import logging
from collections import OrderedDict
from typing import List, Union, Sized, Tuple, Dict
import torch
from torch.nn import Module
from torch.utils.data import IterableDataset
from torch.utils.data.sampler import Sampler
from backpack import extend, backpack
from backpack.extensions import Batch... | 10,988 | 50.834906 | 125 | py |
GraB | GraB-main/src/orderedsampler/sorter/meanbalance.py | import torch
from .sorterbase import Sort
from typing import List, Dict
from torch.nn import Module
class MeanBalance(Sort):
r"""Implement Gradient Balancing using stale mean.
More details can be found in: https://arxiv.org/abs/2205.10733.
Args:
prob_balance (bool): If ``True``, the balancing will... | 4,637 | 40.410714 | 96 | py |
GraB | GraB-main/src/orderedsampler/sorter/sorterbase.py | from typing import Dict, Union
class Sort:
def __init__(self,
prob_balance: bool = False,
per_batch_order: bool = False) -> None:
self.prob_balance = prob_balance
self.per_batch_order = per_batch_order
def reset_epoch(self):
pass
def step(se... | 379 | 26.142857 | 55 | py |
GraB | GraB-main/src/orderedsampler/sorter/utils.py | import torch
from torch import Tensor
from torch.nn import Module
from torch._utils import _flatten_dense_tensors
from typing import Tuple
from collections import OrderedDict
def flatten_batch_grads(model: Module) -> Tensor:
all_grads = []
for param in model.parameters():
if param.grad is not None:
... | 771 | 28.692308 | 78 | py |
GraB | GraB-main/src/orderedsampler/sorter/pairbalance.py | import torch
from .sorterbase import Sort
from typing import List, Dict
from torch.nn import Module
class PairBalance(Sort):
r"""Implement Pair Balance algorithm.
For a given sequence z_i, i = 1, 2, ..., n, we balance z_{2t} - z_{2t-1}.
This avoids using the stale mean as in MeanBalance, and can b... | 7,142 | 43.924528 | 94 | py |
GraB | GraB-main/src/orderedsampler/sorter/subroutine.py | import random
import torch
from torch import Tensor
def deterministic_balance(vec: Tensor, aggregator: Tensor):
if torch.norm(aggregator + vec) <= torch.norm(aggregator - vec):
return 1
else:
return -1
def probabilistic_balance(vec, aggregator):
p = 0.5 - torch.dot(vec, aggregator) / 60
... | 395 | 18.8 | 68 | py |
GraB | GraB-main/src/orderedsampler/sorter/__init__.py | 0 | 0 | 0 | py | |
pke | pke-master/setup.py | from distutils.core import setup
setup(name='pke',
version='2.0.0',
description='Python Keyphrase Extraction module',
author='pke contributors',
author_email='florian.boudin@univ-nantes.fr',
license='gnu',
packages=['pke', 'pke.unsupervised', 'pke.supervised',
'pke.s... | 769 | 28.615385 | 79 | py |
pke | pke-master/pke/base.py | # -*- coding: utf-8 -*-
"""Base classes for the pke module."""
from collections import defaultdict
from pke.data_structures import Candidate
from pke.readers import RawTextReader, SpacyDocReader, PreprocessedReader
from nltk import RegexpParser
from nltk.stem.snowball import SnowballStemmer
from pke.lang import st... | 17,433 | 37.485651 | 139 | py |
pke | pke-master/pke/readers.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Readers for the pke module."""
import logging
import spacy
from pke.data_structures import Sentence
# https://spacy.io/usage/linguistic-features#native-tokenizer-additions
from spacy.lang.char_classes import ALPHA, ALPHA_LOWER, ALPHA_UPPER
from spacy.lang.char_classe... | 5,330 | 34.072368 | 143 | py |
pke | pke-master/pke/lang.py | # -*- coding: utf-8 -*-
"""Language resources of pke.
Lists of stopwords in different languages.
These lists are taken from spacy.
Langcodes.
"""
import importlib
# This dictionnary holds only languages supported by `pke`.
# Supported languages need a stemmer and a spacy model.
# This dictionnary maps spacy's l... | 1,079 | 21.5 | 71 | py |
pke | pke-master/pke/utils.py | # -*- coding: utf-8 -*-
"""Useful functions for the pke module."""
from __future__ import division
from __future__ import absolute_import
from __future__ import print_function
import os
import sys
import csv
import pickle
import gzip
import json
import codecs
import logging
from collections import defaultdict
from... | 14,963 | 34.971154 | 79 | py |
pke | pke-master/pke/__init__.py | from __future__ import absolute_import
from pke.data_structures import Candidate, Sentence
from pke.base import LoadFile
from pke.utils import (
load_document_frequency_file, compute_document_frequency,
train_supervised_model, load_references,
compute_lda_model, load_lda_model)
import pke.unsupervised
impo... | 338 | 29.818182 | 61 | py |
pke | pke-master/pke/data_structures.py | # -*- coding: utf-8 -*-
from dataclasses import dataclass
"""Data structures for the pke module."""
@dataclass
class Sentence:
"""The sentence data structure."""
def __init__(self, words, pos=[], meta={}):
self.words = words
"""list of words (tokens) in the sentence."""
self.pos =... | 1,114 | 21.3 | 61 | py |
pke | pke-master/pke/unsupervised/__init__.py | # -*- coding: utf-8 -*-
# Python Keyphrase Extraction toolkit: unsupervised models
from __future__ import absolute_import
from pke.unsupervised.graph_based.topicrank import TopicRank
from pke.unsupervised.graph_based.singlerank import SingleRank
from pke.unsupervised.graph_based.multipartiterank import MultipartiteRa... | 747 | 40.555556 | 74 | py |
pke | pke-master/pke/unsupervised/statistical/firstphrases.py | # -*- coding: utf-8 -*-
# Author: ygor Gallina
# Date: 19-10-2018
"""StupidKE keyphrase extraction model."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from pke.base import LoadFile
class FirstPhrases(LoadFile):
"""Baseline model that extracts t... | 1,891 | 28.5625 | 80 | py |
pke | pke-master/pke/unsupervised/statistical/tfidf.py | # -*- coding: utf-8 -*-
# Author: Florian Boudin
# Date: 09-10-2018
"""TF-IDF keyphrase extraction model."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import math
import logging
from pke.base import LoadFile
from pke.utils import load_document_frequ... | 2,862 | 30.461538 | 79 | py |
pke | pke-master/pke/unsupervised/statistical/kpminer.py | # -*- coding: utf-8 -*-
# Author: Florian Boudin
# Date: 09-10-2018
"""KP-Miner keyphrase extraction model.
Statistical approach to keyphrase extraction described in:
* Samhaa R. El-Beltagy and Ahmed Rafea.
KP-Miner: Participation in SemEval-2.
*Proceedings of SemEval*, pages 190-193, 2010.
"""
from __future__... | 5,139 | 32.594771 | 78 | py |
pke | pke-master/pke/unsupervised/statistical/yake.py | # -*- coding: utf-8 -*-
# Author: Florian Boudin and Vítor Mangaravite
# Date: 09-10-2018
"""YAKE keyphrase extraction model.
Statistical approach to keyphrase extraction described in:
* Ricardo Campos, Vítor Mangaravite, Arian Pasquali, Alípio Mário Jorge,
Célia Nunes and Adam Jatowt.
YAKE! Keyword extraction f... | 18,089 | 37.903226 | 86 | py |
pke | pke-master/pke/unsupervised/statistical/__init__.py | # -*- coding: utf-8 -*-
# Python Keyphrase Extraction toolkit: unsupervised statistical ranking models
| 103 | 33.666667 | 78 | py |
pke | pke-master/pke/unsupervised/graph_based/single_tpr.py | # -*- coding: utf-8 -*-
# Author: Florian Boudin
# Date: 09-11-2018
"""Single Topical PageRank keyphrase extraction model.
This implementation is an improvement on a keyphrase extraction algorithm,
Topical PageRank (TPR), incorporating topical information from topic model and
described in:
* Lucas Sterckx, Thomas De... | 7,247 | 35.059701 | 88 | py |
pke | pke-master/pke/unsupervised/graph_based/singlerank.py | # -*- coding: utf-8 -*-
# Author: Florian Boudin
# Date: 09-11-2018
"""SingleRank keyphrase extraction model.
Simple extension of the TextRank model described in:
* Xiaojun Wan and Jianguo Xiao.
CollabRank: Towards a Collaborative Approach to Single-Document Keyphrase
Extraction.
*In proceedings of the COLING*... | 5,143 | 35.225352 | 80 | py |
pke | pke-master/pke/unsupervised/graph_based/textrank.py | # -*- coding: utf-8 -*-
# Authors: Ygor Gallina, Florian Boudin
# Date: 10-18-2018
"""TextRank keyphrase extraction model.
Implementation of the TextRank model for keyword extraction described in:
* Rada Mihalcea and Paul Tarau.
TextRank: Bringing Order into Texts
*In Proceedings of EMNLP*, 2004.
"""
from __fu... | 6,822 | 35.682796 | 80 | py |
pke | pke-master/pke/unsupervised/graph_based/multipartiterank.py | # -*- coding: utf-8 -*-
# Author: Florian Boudin
# Date: 09-11-2018
"""Multipartite graph keyphrase extraction model.
Graph-based ranking approach to keyphrase extraction described in:
* Florian Boudin.
Unsupervised Keyphrase Extraction with Multipartite Graphs.
*In proceedings of NAACL*, pages 667-672, 2018.
"... | 7,587 | 32.875 | 77 | py |
pke | pke-master/pke/unsupervised/graph_based/topicrank.py | # -*- coding: utf-8 -*-
# Author: Florian Boudin
# Date: 09-10-2018
"""TopicRank keyphrase extraction model.
Graph-based ranking approach to keyphrase extraction described in:
* Adrien Bougouin, Florian Boudin and Béatrice Daille.
TopicRank: Graph-Based Topic Ranking for Keyphrase Extraction.
*In proceedings of ... | 8,087 | 32.012245 | 85 | py |
pke | pke-master/pke/unsupervised/graph_based/__init__.py | # -*- coding: utf-8 -*-
# Python Keyphrase Extraction toolkit: unsupervised graph-based ranking models
| 103 | 33.666667 | 78 | py |
pke | pke-master/pke/unsupervised/graph_based/positionrank.py | # -*- coding: utf-8 -*-
# Author: Florian Boudin
# Date: 09-11-2018
"""PositionRank keyphrase extraction model.
PositionRank is an unsupervised model for keyphrase extraction from scholarly
documents that incorporates information from all positions of a word's
occurrences into a biased PageRank. The model is describe... | 6,775 | 35.826087 | 80 | py |
pke | pke-master/pke/supervised/api.py | # -*- coding: utf-8 -*-
""" Abstract base class for Supervised models. """
from __future__ import division
from __future__ import absolute_import
import os
from pke.base import LoadFile
from sklearn.preprocessing import MinMaxScaler
from joblib import load as load_model
class SupervisedLoadFile(LoadFile):
"""... | 2,140 | 27.546667 | 84 | py |
pke | pke-master/pke/supervised/__init__.py | # -*- coding: utf-8 -*-
from __future__ import absolute_import
from pke.supervised.api import SupervisedLoadFile
from pke.supervised.feature_based.kea import Kea
from pke.supervised.feature_based.wingnus import WINGNUS
| 220 | 30.571429 | 56 | py |
pke | pke-master/pke/supervised/feature_based/kea.py | # -*- coding: utf-8 -*-
# Author: Florian Boudin
# Date: 09-10-2018
"""Kea supervised keyphrase extraction model.
Kea is a supervised model for keyphrase extraction that uses two features,
namely TF x IDF and first occurrence, to classify keyphrase candidates as
keyphrase or not. The model is described in:
* Ian Wit... | 5,778 | 33.60479 | 79 | py |
pke | pke-master/pke/supervised/feature_based/wingnus.py | # -*- coding: utf-8 -*-
# Author: Florian Boudin
# Date: 09-10-2018
"""Kea keyphrase extraction model.
Supervised approach to keyphrase extraction described in:
* Thuy Dung Nguyen and Minh-Thang Luong.
WINGNUS: Keyphrase Extraction Utilizing Document Logical Structure.
*Proceedings of SemEval*, pages 166–169, 20... | 8,740 | 32.619231 | 90 | py |
pke | pke-master/pke/supervised/feature_based/__init__.py | # -*- coding: utf-8 -*-
| 24 | 11.5 | 23 | py |
pke | pke-master/examples/compute-lda_model.py | # -*- coding: utf-8 -*-
import sys
import logging
from glob import glob
import xml.etree.ElementTree as etree
from pke import compute_lda_model
# setting info in terminal
logging.basicConfig(level=logging.INFO)
# path to the collection of xml documents
input_dir = sys.argv[1]
# path to the lda model, saved as a gz... | 1,646 | 26.915254 | 75 | py |
pke | pke-master/examples/benchmarking-models.py | # -*- coding: utf-8 -*-
import re
import spacy
import numpy as np
from tqdm import tqdm
from spacy.tokenizer import _get_regex_pattern
from datasets import load_dataset
from pke.unsupervised import *
from pke import compute_document_frequency, load_document_frequency_file
# load the inspec dataset
dataset = load_data... | 3,002 | 33.918605 | 117 | py |
pke | pke-master/examples/keyphrase-extraction.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# this example uses TopicRank
from pke.unsupervised import TopicRank
# create a TopicRank extractor
extractor = TopicRank()
# load the content of the document, here in raw text format
# the input language is set to English (used for the stoplist)
# normalization is set t... | 1,069 | 31.424242 | 78 | py |
pke | pke-master/examples/compute-df-counts.py | # -*- coding: utf-8 -*-
import sys
import logging
from glob import glob
from string import punctuation
import xml.etree.ElementTree as etree
from pke import compute_document_frequency
# setting info in terminal
logging.basicConfig(level=logging.INFO)
# path to the collection of xml documents
input_dir = sys.argv[1]... | 1,841 | 28.238095 | 75 | py |
pke | pke-master/examples/training_and_testing_a_kea_model/test.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import pke
base = os.path.dirname(__file__)
# create a Kea extractor and set the input language to English (used for
# the stoplist in the candidate selection method)
extractor = pke.supervised.Kea()
# load the content of the document, here in corenlp format
... | 941 | 25.166667 | 77 | py |
pke | pke-master/examples/training_and_testing_a_kea_model/train.py | # -*- coding: utf-8 -*-
import os
import logging
from glob import glob
import pke
# setting info in terminal
logging.basicConfig(level=logging.INFO)
base = os.path.dirname(__file__)
# path to the collection of documents
documents = []
for fn in glob(base + os.sep + 'train/*.txt'):
with open(fn) as f:
do... | 1,168 | 23.354167 | 58 | py |
pke | pke-master/tests/sample.py | # -*- coding: utf-8 -*
import spacy
nlp = spacy.load("en_core_web_sm")
sample = """Inverse problems for a mathematical model of ion exchange in a compressible ion exchanger.
A mathematical model of ion exchange is considered, allowing for ion exchanger compression in the process
of ion exchange. Two inverse problems... | 2,140 | 68.064516 | 118 | py |
pke | pke-master/tests/test_reading.py | # -*- coding: utf-8 -*-
import pke
from .sample import sample, sample_doc, sample_list
def test_reading():
# loading from string
extractor1 = pke.base.LoadFile()
extractor1.load_document(sample)
# loading from string
extractor2 = pke.base.LoadFile()
extractor2.load_document(sample_doc)
... | 759 | 25.206897 | 116 | py |
pke | pke-master/tests/test_firstphrases.py | # -*- coding: utf-8 -*-
import pke
from .sample import sample_list
valid_pos = {'NOUN', 'PROPN', 'ADJ'}
def test_firstphrases_candidate_selection():
extractor = pke.unsupervised.FirstPhrases()
extractor.load_document(input=sample_list)
extractor.candidate_selection(pos=valid_pos)
assert len(extracto... | 827 | 28.571429 | 83 | py |
pke | pke-master/tests/__init__.py | 0 | 0 | 0 | py | |
pke | pke-master/tests/test_utils.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import pke
data_path = os.path.join('tests', 'data')
def create_df(corpus, tmp_path, name='corpus_df.gz'):
df_file = tmp_path / name
pke.utils.compute_document_frequency(
corpus, str(df_file), n=1)
corpus_df = pke.utils.load_document_freque... | 3,645 | 31.553571 | 90 | py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.