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
attention-is-all-you-need-pytorch
attention-is-all-you-need-pytorch-master/transformer/SubLayers.py
''' Define the sublayers in encoder/decoder layer ''' import numpy as np import torch.nn as nn import torch.nn.functional as F from transformer.Modules import ScaledDotProductAttention __author__ = "Yu-Hsiang Huang" class MultiHeadAttention(nn.Module): ''' Multi-Head Attention module ''' def __init__(self, n...
2,606
30.409639
96
py
attention-is-all-you-need-pytorch
attention-is-all-you-need-pytorch-master/transformer/Modules.py
import torch import torch.nn as nn import torch.nn.functional as F __author__ = "Yu-Hsiang Huang" class ScaledDotProductAttention(nn.Module): ''' Scaled Dot-Product Attention ''' def __init__(self, temperature, attn_dropout=0.1): super().__init__() self.temperature = temperature self....
674
24.961538
68
py
attention-is-all-you-need-pytorch
attention-is-all-you-need-pytorch-master/transformer/Models.py
''' Define the Transformer model ''' import torch import torch.nn as nn import numpy as np from transformer.Layers import EncoderLayer, DecoderLayer __author__ = "Yu-Hsiang Huang" def get_pad_mask(seq, pad_idx): return (seq != pad_idx).unsqueeze(-2) def get_subsequent_mask(seq): ''' For masking out the su...
7,678
37.58794
99
py
easyreg
easyreg-master/setup.py
#!/usr/bin/env python # -*- coding: utf-8 -*- # Note: To use the 'upload' functionality of this file, you must: # $ pipenv install twine --dev import io import os import sys from shutil import rmtree from setuptools import find_packages, setup, Command from version import get_git_version # Package meta-data. NAME...
4,359
26.080745
86
py
easyreg
easyreg-master/tools/draw_deformation.py
import numpy as np import sys,os os.environ["CUDA_VISIBLE_DEVICES"] = '' from easyreg.viewers import * from mermaid.utils import * from mermaid.data_utils import * import SimpleITK as sitk from glob import glob import os sz = [160,200,200] def get_image_list_to_draw(refer_folder,momentum_folder,img_type,source_targ...
12,626
52.731915
210
py
easyreg
easyreg-master/tools/transform_disp_into_torch_form.py
import nibabel as nib import numpy as np def transform_disp_into_torch_form(inv_transform_file): inv_map = nib.load(inv_transform_file) inv_map = inv_map.get_fdata() assert inv_map.shape[0]==3 inv_map = np.transpose(inv_map,[3,2,1,0]) return inv_map
271
26.2
55
py
easyreg
easyreg-master/tools/draw_deformation_2d.py
import os os.environ["CUDA_VISIBLE_DEVICES"] = '' from tools.draw_deformation_viewers import * from mermaid.utils import * from mermaid.data_utils import * from glob import glob sz = [160,200,200] def get_image_list_to_draw(refer_folder,momentum_folder,img_type,source_target_folder,t_list): """ we first need ...
18,322
52.110145
222
py
easyreg
easyreg-master/tools/transform_between_mermaid_and_itk.py
import SimpleITK as sitk import numpy as np import os from easyreg.utils import resample_image from mermaid.utils import compute_warped_image_multiNC import torch from easyreg.net_utils import gen_identity_map from easyreg.demons_utils import sitk_grid_sampling import tools.image_rescale as ires # img_org_path = "/pl...
5,800
50.794643
221
py
easyreg
easyreg-master/tools/warp_image_label.py
import os os.environ["CUDA_VISIBLE_DEVICES"] = '' from easyreg.reg_data_utils import read_txt_into_list, get_file_name from tools.image_rescale import save_image_with_given_reference import SimpleITK as sitk import torch import numpy as np from glob import glob from mermaid.utils import compute_warped_image_multiNC, re...
2,617
49.346154
172
py
easyreg
easyreg-master/tools/visual_tools.py
import matplotlib.pyplot as plt from easyreg import utils import SimpleITK as sitk import torch import numpy as np import mermaid.finite_differences as fdt import mermaid.utils as py_utils import os from scipy import misc def read_png_into_numpy(file_path,name=None,visual=False): image = misc.imread(file_path,fla...
7,597
31.75
121
py
easyreg
easyreg-master/tools/print_sh.py
import os def print_txt(txt, output_path): with open(output_path,"w") as f: f.write(txt) key_w_list = [10,20,30,40,60,80,100] key_w_list2= ["1d","atlas",'rand','bspline','aug'] for key_w2 in key_w_list2: output_path = '/playpen-raid/zyshen/debug/llf_output/par/oai_seg_{}'.format(key_w2) os...
7,499
37.265306
400
py
easyreg
easyreg-master/tools/image_rescale.py
import SimpleITK as sitk from easyreg.reg_data_utils import write_list_into_txt, generate_pair_name from easyreg.utils import * import mermaid.utils as py_utils from mermaid.data_wrapper import MyTensor def __read_and_clean_itk_info(input): if isinstance(input,str): return sitk.GetImageFromArray(sitk.Get...
13,185
42.375
158
py
easyreg
easyreg-master/data_pre/fileio.py
""" Helper functions to take care of all the file IO """ import itk import os import nrrd import torch import data_pre.image_manipulations as IM import numpy as np from abc import ABCMeta, abstractmethod class FileIO(object): """ Abstract base class for file i/o. """ __metaclass__ = ABCMeta def ...
17,393
36.568035
127
py
easyreg
easyreg-master/data_pre/partition_multi_channel.py
import numpy as np import SimpleITK as sitk def partition_multi(option_p, patch_size,overlap_size, mode=None, img_sz=(-1,-1,-1), flicker_on=False, flicker_mode='rand'): padding_mode = option_p[('padding_mode', 'reflect', 'padding_mode')] mode = mode if mode is not None else option_p[('mode', 'pred', 'eval or ...
9,615
53.636364
187
py
easyreg
easyreg-master/data_pre/transform_pool.py
""" classes of transformations for 3d simpleITK image """ import threading import SimpleITK as sitk import numpy as np import torch import math import random import time from math import floor class Resample(object): """Resample the volume in a sample to a given voxel size Args: voxel_size (float or...
29,747
36.513241
140
py
easyreg
easyreg-master/data_pre/partition.py
import numpy as np import SimpleITK as sitk def partition(option_p, patch_size,overlap_size, mode=None, img_sz=(-1,-1,-1), flicker_on=False, flicker_mode='rand'): padding_mode = option_p[('padding_mode', 'reflect', 'padding_mode')] mode = mode if mode is not None else option_p[('mode', 'pred', 'eval or pred')...
13,186
54.64135
181
py
easyreg
easyreg-master/data_pre/reg_preprocess_example/utils.py
import os from easyreg.reg_data_utils import loading_img_list_from_files,generate_pair_name local_path = "/playpen-raid/zyshen/oai_data" server_path = "/pine/scr/z/y/zyshen/data/oai_data" switcher = (local_path, server_path) def server_switcher(f_path,switcher=("","")): if len(switcher[0]): f_path = f_pa...
4,748
41.026549
164
py
easyreg
easyreg-master/data_pre/reg_preprocess_example/stik_resize_vs_mermaid_resize.py
import numpy as np import SimpleITK as sitk from easyreg.utils import get_resampled_image import torch def resize_img(img, is_label=False,img_after_resize=None): """ :param img: sitk input, factor is the outputs_ize/patched_sized :return: """ img_sz = img.GetSize() if img_after_resize is None: ...
2,843
40.823529
135
py
easyreg
easyreg-master/data_pre/reg_preprocess_example/gen_from_brainstorm.py
""" Input txt for atlas to image , i.e. train txt atlas, image, atlas_label folder for color image folder for transformation """ import matplotlib as matplt matplt.use('Agg') import sys,os os.environ["CUDA_VISIBLE_DEVICES"] = '' sys.path.insert(0,os.path.abspath('.')) sys.path.insert(0,os.path.abspath('..')) sys.path...
11,645
57.818182
170
py
easyreg
easyreg-master/data_pre/reg_preprocess_example/get_atlas_label.py
import os import SimpleITK as sitk from mermaid.utils import compute_warped_image_multiNC from easyreg.reg_data_utils import * from tools.image_rescale import save_image_with_given_reference from glob import glob import numpy as np import torch from easyreg.metrics import * from functools import reduce def make_one_h...
4,342
45.698925
128
py
easyreg
easyreg-master/data_pre/reg_preprocess_example/dirlab_eval.py
import os import json import numpy as np import torch import SimpleITK as sitk import pyvista as pv import mermaid.utils as py_utils from data_pre.reg_preprocess_example.vtk_utils import save_vtk from tools.visual_tools import save_3D_img_from_numpy COPD_ID=[ "copd_000001", "copd_000002", "copd_000003", "c...
14,618
52.746324
195
py
easyreg
easyreg-master/demo/hack.py
import os import numpy as np import torch import SimpleITK as sitk import pyvista as pv from easyreg.net_utils import gen_identity_map from tools.image_rescale import permute_trans from tools.module_parameters import ParameterDict from easyreg.multiscale_net_improved import Multiscale_FlowNet as model from easyreg.util...
21,097
44.765727
232
py
easyreg
easyreg-master/demo/demo_for_data_aug.py
""" A demo for fluid-based data augmentation. """ import matplotlib as matplt import subprocess matplt.use('Agg') import os, sys, time import torch torch.backends.cudnn.benchmark=True sys.path.insert(0, os.path.abspath('..')) sys.path.insert(0, os.path.abspath('.')) sys.path.insert(0, os.path.abspath('../easy_reg')) ...
12,841
52.066116
201
py
easyreg
easyreg-master/demo/demo_for_easyreg_train.py
import matplotlib as matplt matplt.use('Agg') import os, sys sys.path.insert(0,os.path.abspath('..')) sys.path.insert(0,os.path.abspath('.')) sys.path.insert(0,os.path.abspath('../easy_reg')) #sys.path.insert(0,os.path.abspath('../mermaid')) import numpy as np import torch import random torch.backends.cudnn.benchmark=T...
10,865
42.464
201
py
easyreg
easyreg-master/demo/demo_for_seg_train.py
import matplotlib as matplt matplt.use('Agg') import os, sys sys.path.insert(0,os.path.abspath('..')) sys.path.insert(0,os.path.abspath('.')) sys.path.insert(0,os.path.abspath('../easyreg')) import numpy as np import torch import random import tools.module_parameters as pars from abc import ABCMeta, abstractmethod from...
6,756
35.722826
152
py
easyreg
easyreg-master/demo/hack_v2.py
import os import numpy as np import torch import SimpleITK as sitk import pyvista as pv from easyreg.net_utils import gen_identity_map from tools.image_rescale import permute_trans from tools.module_parameters import ParameterDict from easyreg.lin_unpublic_net import model from easyreg.utils import resample_image, get_...
21,573
43.209016
204
py
easyreg
easyreg-master/demo/oai_eval.py
import os import numpy as np import torch import SimpleITK as sitk from tools.module_parameters import ParameterDict from easyreg.mermaid_net import MermaidNet as model from easyreg.utils import resample_image import mermaid.utils as py_utils def resize_img(img, img_after_resize=None, is_mask=False): """ :par...
7,086
48.559441
184
py
easyreg
easyreg-master/demo/gen_aug_samples.py
import matplotlib as matplt matplt.use('Agg') import sys,os #os.environ["CUDA_VISIBLE_DEVICES"] = '' sys.path.insert(0,os.path.abspath('..')) sys.path.insert(0,os.path.abspath('../easyreg')) sys.path.insert(0,os.path.abspath('.')) import random import torch from mermaid.model_evaluation import evaluate_model import me...
47,706
54.280417
235
py
easyreg
easyreg-master/demo/demo_for_seg_eval.py
import matplotlib as matplt matplt.use('Agg') import os, sys sys.path.insert(0, os.path.abspath('..')) sys.path.insert(0, os.path.abspath('.')) sys.path.insert(0, os.path.abspath('../easy_reg')) import tools.module_parameters as pars from abc import ABCMeta, abstractmethod from easyreg.piplines import run_one_task f...
9,097
41.915094
152
py
easyreg
easyreg-master/easyreg/seg_net.py
from .base_seg_model import SegModelBase from .net_utils import print_network from .losses import Loss import torch.optim.lr_scheduler as lr_scheduler from .utils import * from .seg_unet import SegUnet from .metrics import get_multi_metric model_pool = { 'seg_unet': SegUnet, } class SegNet(SegModelBase): """...
8,036
33.943478
147
py
easyreg
easyreg-master/easyreg/affine_net.py
from __future__ import absolute_import from __future__ import division from __future__ import print_function from .modules import * from .net_utils import Bilinear from torch.utils.checkpoint import checkpoint from .utils import sigmoid_decay from .losses import NCCLoss class AffineNetSym(nn.Module): """ A ...
19,504
43.329545
212
py
easyreg
easyreg-master/easyreg/losses.py
# coding=utf-8 import torch import numpy as np import torch.nn as nn import torch.nn.functional as F import mermaid.finite_differences as fdt ############################################################################### # Functions ############################################################################### clas...
21,306
38.826168
152
py
easyreg
easyreg-master/easyreg/seg_unet.py
from .modules import Seg_resid from .utils import * import torch.nn as nn from data_pre.partition import partition class SegUnet(nn.Module): def __init__(self, opt=None): super(SegUnet, self).__init__() self.opt = opt seg_opt = opt['tsk_set'][('seg',{},"settings for seg task")] sel...
10,717
47.497738
190
py
easyreg
easyreg-master/easyreg/seg_data_loader_onfly.py
from __future__ import print_function, division import blosc import torch from torch.utils.data import Dataset from data_pre.seg_data_utils import * from data_pre.transform import Transform import SimpleITK as sitk from multiprocessing import * blosc.set_nthreads(1) import progressbar as pb from copy import deepcopy im...
21,752
44.413361
186
py
easyreg
easyreg-master/easyreg/multiscale_net.py
""" """ import copy from .losses import NCCLoss, Loss from .net_utils import gen_identity_map import mermaid.finite_differences_multi_channel as fdt import numpy as np import torch import torch.nn as nn import torch.nn.functional as F from .net_utils import Bilinear from mermaid.libraries.modules import stn_nd from .af...
21,795
50.649289
178
py
easyreg
easyreg-master/easyreg/modules.py
from __future__ import absolute_import from __future__ import division from __future__ import print_function import mermaid.utils as py_utils import torch from .net_utils import * class Affine_unet(nn.Module): def __init__(self): super(Affine_unet,self).__init__() #(W−F+2P)/S+1, W - input siz...
21,891
53.593516
127
py
easyreg
easyreg-master/easyreg/brainstorm.py
""" Framework described in Data augmentation using learned transformationsfor one-shot medical image segmentation http://www.mit.edu/~adalca/files/papers/cvpr2019_brainstorm.pdf """ from .net_utils import gen_identity_map import mermaid.finite_differences as fdt import numpy as np import torch import torch.nn as nn im...
14,398
38.449315
120
py
easyreg
easyreg-master/easyreg/base_mermaid.py
from time import time from .base_reg_model import RegModelBase from .utils import * import mermaid.finite_differences as fdt from mermaid.utils import compute_warped_image_multiNC import tools.image_rescale as ires from .metrics import get_multi_metric import SimpleITK as sitk class MermaidBase(RegModelBase): ""...
20,184
54.30137
171
py
easyreg
easyreg-master/easyreg/voxel_morph.py
""" registration network described in voxelmorph An experimental pytorch implemetation, the official tensorflow please refers to https://github.com/voxelmorph/voxelmorph An Unsupervised Learning Model for Deformable Medical Image Registration Guha Balakrishnan, Amy Zhao, Mert R. Sabuncu, John Guttag, Adrian V. Dalca C...
25,457
40.194175
171
py
easyreg
easyreg-master/easyreg/mermaid_net.py
from __future__ import absolute_import from __future__ import division from __future__ import print_function from .utils import * from .affine_net import * from .momentum_net import * import mermaid.module_parameters as pars import mermaid.model_factory as py_mf import mermaid.utils as py_utils from functools import p...
34,904
47.479167
175
py
easyreg
easyreg-master/easyreg/reg_net.py
from .base_mermaid import MermaidBase from .affine_net import * from .net_utils import print_network from .losses import Loss import torch.optim.lr_scheduler as lr_scheduler from .utils import * from .mermaid_net import MermaidNet from .voxel_morph import VoxelMorphCVPR2018, VoxelMorphMICCAI2019 # from .multiscale_net_...
10,289
37.111111
147
py
easyreg
easyreg-master/easyreg/utils.py
import torch import numpy as np import skimage import os import torchvision.utils as utils import SimpleITK as sitk from skimage import color import mermaid.image_sampling as py_is from mermaid.data_wrapper import AdaptVal,MyTensor from .net_utils import gen_identity_map from .net_utils import Bilinear import mermaid.u...
22,136
36.142617
157
py
easyreg
easyreg-master/easyreg/train_expr.py
from time import time from .net_utils import * def train_model(opt,model, dataloaders,writer): since = time() print_step = opt['tsk_set'][('print_step', [10,4,4], 'num of steps to print')] num_epochs = opt['tsk_set'][('epoch', 100, 'num of training epoch')] continue_train = opt['tsk_set'][('continue...
10,456
48.795238
164
py
easyreg
easyreg-master/easyreg/base_seg_model.py
from .utils import * import SimpleITK as sitk from tools.visual_tools import save_3D_img_from_numpy class SegModelBase(): """ the base class for image segmentation """ def name(self): return 'SegModelBase' def initialize(self, opt): """ :param opt: ParameterDict, task se...
7,185
26.961089
152
py
easyreg
easyreg-master/easyreg/compare_sym.py
import torch import numpy as np import sys,os import SimpleITK as sitk from easyreg.net_utils import Bilinear import ants from .nifty_reg_utils import nifty_reg_resample import subprocess import nibabel as nib from mermaid.utils import identity_map_multiN # record_path ='/playpen/zyshen/debugs/compare_sym' # moving_...
9,171
39.764444
142
py
easyreg
easyreg-master/easyreg/mermaid_iter.py
from .base_mermaid import MermaidBase from .utils import * import mermaid.utils as py_utils import mermaid.simple_interface as SI class MermaidIter(MermaidBase): def name(self): return 'mermaid-iter' def initialize(self,opt): """ :param opt: ParameterDict, task settings :return:...
12,862
41.3125
189
py
easyreg
easyreg-master/easyreg/data_manager.py
from easyreg.reg_data_utils import * from torchvision import transforms import torch from easyreg import reg_data_loader_onfly as reg_loader_of from easyreg import seg_data_loader_onfly as seg_loader_of from easyreg.reg_data_loader_onfly import ToTensor # todo reformat the import style class DataManager(object): de...
8,907
39.126126
152
py
easyreg
easyreg-master/easyreg/reg_data_loader_onfly.py
from __future__ import print_function, division import blosc import torch from torch.utils.data import Dataset from .reg_data_utils import * import SimpleITK as sitk from multiprocessing import * blosc.set_nthreads(1) import progressbar as pb class RegistrationDataset(Dataset): """registration dataset.""" def...
17,753
44.175573
186
py
easyreg
easyreg-master/easyreg/create_model.py
import torch def create_model(opt): """ create registration model object :param opt: ParameterDict, task setting :return: model object """ model = None model_name = opt['tsk_set']['model'] gpu_id = opt['tsk_set']['gpu_ids'] sz = opt # gpu_count = torch.cuda.device_count() # p...
1,615
33.382979
104
py
easyreg
easyreg-master/easyreg/net_utils.py
import torch import torch.nn as nn import torch.nn.functional as F from torch.nn import Module import numpy as np import torch.nn.init as init import os from easyreg.reproduce_paper_results import reproduce_paper_result dim = 3 Conv = nn.Conv2d if dim == 2 else nn.Conv3d MaxPool = nn.MaxPool2d if dim == 2 else nn.MaxP...
17,530
33.107004
172
py
easyreg
easyreg-master/doc/source/conf.py
# -*- coding: utf-8 -*- # # pytorchRegistration documentation build configuration file, created by # sphinx-quickstart on Sat Jul 29 08:41:36 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...
13,865
30.585421
143
py
point_clouds_registration_benchmark
point_clouds_registration_benchmark-master/devel/generate_pcd_kaist.py
import argparse import os import sys sys.path.append("..") sys.path.append(".") import h5py import numpy as np import torch import open3d as o3 from tqdm import tqdm def load_cloud(stamp, folder, pose, calib_pose): pc_file = os.path.join(folder, f'{stamp}.bin') pc = np.fromfile(pc_file, dtype=np.float32) ...
5,242
29.841176
93
py
SPARQA
SPARQA-master/code/common/bert_args.py
class BertArgs(): def __init__(self, root, mode): # uncased model self.bert_base_uncased_model = root + '/pre_train_models/bert-base-uncased.tar.gz' self.bert_base_uncased_tokenization = root + '/pre_train_models/bert-base-uncased-vocab.txt' # cased model self.bert_base_cas...
1,967
58.636364
118
py
SPARQA
SPARQA-master/code/parsing/models/fine_tuning_based_on_bert_interface/token_classifier_interface.py
from parsing.parsing_args import bert_args from parsing.models.fine_tuning_based_on_bert.run_token_classifier import NodeRecogniationProcessor, convert_example_to_features_for_test from parsing.models import model_utils import sys import os import random import numpy as np import torch from torch.utils.data import Tens...
3,666
46.623377
137
py
SPARQA
SPARQA-master/code/parsing/models/fine_tuning_based_on_bert_interface/simplif_classifier_interface.py
import numpy as np import torch from torch.utils.data import TensorDataset, DataLoader, SequentialSampler from parsing.models import model_utils from parsing.models.fine_tuning_based_on_bert.run_sequence_classifier import \ SimplificationQuestionProcessor, convert_examples_to_features from parsing.models.pytorch_pr...
2,937
51.464286
122
py
SPARQA
SPARQA-master/code/parsing/models/fine_tuning_based_on_bert_interface/paraphrase_classifier_interface.py
import numpy as np import torch from torch.utils.data import TensorDataset, DataLoader, SequentialSampler from parsing.models import model_utils from parsing.models.fine_tuning_based_on_bert.run_sequence_classifier import ParaphraseProcess, convert_examples_to_features from parsing.models.pytorch_pretrained_bert import...
2,998
51.614035
133
py
SPARQA
SPARQA-master/code/parsing/models/fine_tuning_based_on_bert_interface/redundancy_span_interface.py
import torch from tqdm import tqdm from torch.utils.data import TensorDataset, DataLoader, SequentialSampler from parsing.models.pytorch_pretrained_bert.tokenization import BertTokenizer from parsing.models.pytorch_pretrained_bert.modeling import BertForQuestionAnswering from parsing.models.fine_tuning_based_on_bert.r...
3,128
58.037736
134
py
SPARQA
SPARQA-master/code/parsing/models/fine_tuning_based_on_bert_interface/sequences_classifier_interface.py
import numpy as np import torch from torch.utils.data import TensorDataset, DataLoader, SequentialSampler from parsing.models import model_utils from parsing.models.fine_tuning_based_on_bert.run_sequence_classifier import SequencesRelationProcess, ParaphraseProcess,\ SimplificationQuestionProcessor, convert_example...
4,410
52.792683
145
py
SPARQA
SPARQA-master/code/parsing/models/fine_tuning_based_on_bert_interface/headword_span_interface.py
import torch from tqdm import tqdm from torch.utils.data import TensorDataset, DataLoader, SequentialSampler from parsing.models.pytorch_pretrained_bert.tokenization import BertTokenizer from parsing.models.pytorch_pretrained_bert.modeling import BertForQuestionAnswering from parsing.models.fine_tuning_based_on_bert.ru...
3,612
60.237288
142
py
SPARQA
SPARQA-master/code/parsing/models/fine_tuning_based_on_bert_interface/joint_three_models_interface.py
import torch from tqdm import tqdm from torch.utils.data import TensorDataset, DataLoader, SequentialSampler from parsing.models.pytorch_pretrained_bert.tokenization import BertTokenizer from parsing.models.pytorch_pretrained_bert.modeling import BertForSpanWithHeadwordWithLabel from parsing.models import model_utils ...
4,168
56.902778
147
py
SPARQA
SPARQA-master/code/parsing/models/fine_tuning_based_on_bert/run_sequence_classifier.py
"""BERT finetuning runner.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import csv import random from tqdm import tqdm, trange import numpy as np import torch from torch.utils.data import TensorDataset, DataLoader, RandomSampler, SequentialSampler from ...
28,072
40.9
134
py
SPARQA
SPARQA-master/code/parsing/models/fine_tuning_based_on_bert/run_redundancy_span.py
import torch import collections import random import numpy as np import pickle import json import sys import os #--------------------------------- from tqdm import tqdm, trange from torch.utils.data import TensorDataset, DataLoader, RandomSampler, SequentialSampler from torch.utils.data.distributed import DistributedSa...
35,296
45.321522
141
py
SPARQA
SPARQA-master/code/parsing/models/fine_tuning_based_on_bert/run_token_classifier.py
"""BERT finetuning runner.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import sys import mmap import csv import os import random from tqdm import tqdm, trange import numpy as np import torch from torch.utils.data import TensorDataset, DataLoader, Rando...
21,450
42.867076
134
py
SPARQA
SPARQA-master/code/parsing/models/fine_tuning_based_on_bert/run_headword_span.py
"""Run BERT on SQuAD.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import collections import json import random import pickle from tqdm import tqdm, trange import numpy as np import torch from torch.utils.data import TensorDataset, DataLoader, RandomS...
38,538
45.884428
141
py
SPARQA
SPARQA-master/code/parsing/models/fine_tuning_based_on_bert/run_joint_three_models.py
import logging import collections import torch import random import numpy as np import pickle from torch.utils.data.distributed import DistributedSampler from torch.utils.data import TensorDataset, DataLoader, RandomSampler, SequentialSampler from tqdm import tqdm, trange import json import sys import os #-------------...
46,532
48.293432
265
py
SPARQA
SPARQA-master/code/parsing/models/fine_tuning_based_on_bert/span_utils.py
import collections import mmap from parsing.models.pytorch_pretrained_bert.tokenization import BasicTokenizer import re import math def warmup_linear(x, warmup=0.002): if x < warmup: return x/warmup return 1.0 - x def _compute_softmax(scores): """Compute softmax probability over raw logits.""" ...
9,725
40.211864
109
py
SPARQA
SPARQA-master/code/parsing/models/pytorch_pretrained_bert/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...
6,785
41.149068
116
py
SPARQA
SPARQA-master/code/parsing/models/pytorch_pretrained_bert/__main__.py
# coding: utf8 def main(): import sys try: from .convert_tf_checkpoint_to_pytorch import convert_tf_checkpoint_to_pytorch except ModuleNotFoundError: print("pytorch_pretrained_bert can only be used from the commandline to convert TensorFlow models in PyTorch, " "In that case, i...
932
39.565217
137
py
SPARQA
SPARQA-master/code/parsing/models/pytorch_pretrained_bert/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...
80,774
49.962145
134
py
SPARQA
SPARQA-master/code/parsing/models/pytorch_pretrained_bert/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 os import logging import shutil import tempfile import json from urllib.parse import urlparse from pathlib import Path from typing ...
8,021
32.425
98
py
SPARQA
SPARQA-master/code/parsing/models/pytorch_pretrained_bert/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 ...
4,463
38.504425
101
py
SPARQA
SPARQA-master/code/grounding/grounding_utils.py
from common_structs.graph import Graph from common_structs.grounded_graph import GrounedGraph from common_structs.depth_first_paths import DepthFirstPaths from common_structs.graph import Digragh from common_structs.cycle import DirectedCycle import mmap import torch def posword_wordlist(posword_list): '''get word...
9,563
33.652174
124
py
SPARQA
SPARQA-master/code/grounding/ranking/path_match_nn/path_match_interface.py
import torch from torch.autograd import Variable from common.globals_args import fn_graph_file, fn_cwq_file, kb_freebase_latest_file, kb_freebase_en_2013, q_mode as mode from common.hand_files import read_json from grounding.ranking.path_match_nn.parameters import get_parameters from grounding.ranking.path_match_nn.wo...
6,405
52.383333
152
py
SPARQA
SPARQA-master/code/grounding/ranking/path_match_nn/train_test_path_nn.py
# -*- coding: utf-8 -*- import torch import torch.optim as optim from common.globals_args import root, fn_graph_file from grounding.ranking.path_match_nn.sequence_loader import SeqRankingLoader from grounding.ranking.path_match_nn.model import PathRanking from grounding.ranking.path_match_nn.parameters import get_para...
4,703
45.574257
114
py
SPARQA
SPARQA-master/code/grounding/ranking/path_match_nn/wordvec.py
import time import torch from grounding.grounding_args import glove_file from grounding.grounding_utils import load_word2vec_format class WordEmbedding(): def __init__(self): # self.pretrained = dict() self.pretrained = load_word2vec_format(glove_file) self.train_generation_embedding = dic...
1,100
38.321429
105
py
SPARQA
SPARQA-master/code/grounding/ranking/path_match_nn/model.py
import torch from torch import nn class PathRanking(nn.Module): def __init__(self,model_parameters): super(PathRanking, self).__init__() self.model_parameters=model_parameters self.fc1 = nn.Sequential(nn.Linear(self.model_parameters.max_question_word, 1)) self.fc2 = nn.Sequential(n...
2,577
45.872727
89
py
SPARQA
SPARQA-master/code/grounding/ranking/path_match_nn/sequence_loader.py
import torch from torch.autograd import Variable class SeqRankingLoader(): def __init__(self, infile, model_parameters,device=-1): self.pos_ques_pathsimmax_list, self.pos_path_quessimmax_list, self.pos_path_len_list,\ self.neg_ques_pathsimmax_list, self.neg_path_quessimmax_list, self.neg_path_len_...
3,553
54.53125
141
py
SPARQA
SPARQA-master/code/grounding/ranking/path_match_nn/path_match_word_utils.py
import collections import torch from sklearn.metrics.pairwise import cosine_similarity def get_qid_abstractquestion(any_2_1): print(len(any_2_1)) qid_abstractquestions=collections.defaultdict(set) for one in any_2_1: qid=one.qid question=one.question for ungrounded_graph in one.ungr...
2,622
37.014493
164
py
SPARQA
SPARQA-master/code/grounding/ranking/path_match_nn/preproccess_freebase.py
import os import copy import torch from common.globals_args import fn_cwq_file, fn_graph_file, root, argument_parser, kb_freebase_latest_file, kb_freebase_en_2013 from common.hand_files import read_json, write_json, read_structure_file import random from grounding.ranking.path_match_nn.wordvec import WordEmbedding fro...
20,297
49.618454
202
py
Bleualign
Bleualign-master/bleualign/utils.py
#!/usr/bin/python # -*- coding: utf-8 -*- # Copyright: University of Zurich # Author: Rico Sennrich # For licensing information, see LICENSE # Evaluation functions for Bleualign from __future__ import division from operator import itemgetter def evaluate(options, testalign, goldalign, log_function): goldalign ...
6,441
32.552083
129
py
acrobat_submission
acrobat_submission-main/utils.py
import pandas as pd from PIL import ImageOps from PIL import ImageFilter import cv2 from torch.utils.data import DataLoader import numpy as np from tqdm import tqdm from torchvision import transforms from torchvision import models import torch from openslide import OpenSlide from PIL import Image from lr_utils import W...
17,079
35.340426
142
py
acrobat_submission
acrobat_submission-main/lr_utils.py
from torch.utils.data import Dataset class WSIDataset(Dataset): def __init__(self, df, wsi, transform, level=0, ps=256): self.wsi = wsi self.transform = transform self.df = df self.level = level self.ps = ps def __len__(self): return len(self.df) def __geti...
629
27.636364
76
py
CX_GAN
CX_GAN-master/Cascaded Model/BRATS Data/implementation/Save BRATS data to Numpy Files.py
# -*- coding: utf-8 -*- """ Created on Thu Feb 27 09:08:06 2020 @author: ZeeshanNisar """ from keras.preprocessing.image import load_img, img_to_array from tqdm import tqdm as tqdm import os import numpy as np img_rows = 256 img_cols = 256 channels = 1 os.chdir('/content/drive/My Drive/GitHub Repositories') baseDir...
1,286
31.175
86
py
FFPerceptron
FFPerceptron-main/FFperceptron_MNIST.py
import torch import time from torchvision.datasets import MNIST from torchvision.transforms import Compose, ToTensor, Normalize, Lambda from torch.utils.data import DataLoader def one_hot_encode(img0, lab): img = img0.clone() img[:, :10] = img0.min() img[range(img0.shape[0]), lab] = img0.max() return ...
3,528
32.932692
134
py
hyperband
hyperband-master/main.py
#!/usr/bin/env python "a more polished example of using hyperband" "includes displaying best results and saving to a file" import sys import cPickle as pickle from pprint import pprint from hyperband import Hyperband #from defs.gb import get_params, try_params #from defs.rf import get_params, try_params #from defs....
1,320
26.520833
73
py
hyperband
hyperband-master/defs/xgb.py
"function (and parameter space) definitions for hyperband" "binary classification with XGBoost" from common_defs import * # a dict with x_train, y_train, x_test, y_test from load_data import data from xgboost import XGBClassifier as XGB # trees_per_iteration = 5 space = { 'learning_rate': hp.choice( 'lr', [ 'd...
1,710
20.123457
67
py
hyperband
hyperband-master/defs/keras_mlp.py
"function (and parameter space) definitions for hyperband" "binary classification with Keras (multilayer perceptron)" from common_defs import * # a dict with x_train, y_train, x_test, y_test from load_data import data from keras.models import Sequential from keras.layers.core import Dense, Dropout from keras.layers....
4,624
30.678082
94
py
hyperband
hyperband-master/defs/meta.py
# meta classifier from common_defs import * models = ( 'xgb', 'gb', 'rf', 'xt', 'sgd', 'polylearn_fm', 'polylearn_pn', 'keras_mlp' ) # import all the functions for m in models: exec( "from defs.{} import get_params as get_params_{}" ).format( m, m ) exec( "from defs.{} import try_params as try_params_{}" ).format( ...
715
25.518519
88
py
hyperband
hyperband-master/defs_regression/xgb.py
"function (and parameter space) definitions for hyperband" "regression with XGBoost" from common_defs import * # a dict with x_train, y_train, x_test, y_test from load_data_for_regression import data from xgboost import XGBRegressor as XGB # trees_per_iteration = 5 space = { 'learning_rate': hp.choice( 'lr', [ ...
1,716
20.197531
67
py
hyperband
hyperband-master/defs_regression/keras_mlp.py
"function (and parameter space) definitions for hyperband" "regression with Keras (multilayer perceptron)" from common_defs import * # a dict with x_train, y_train, x_test, y_test from load_data_for_regression import data from keras.models import Sequential from keras.layers.core import Dense, Dropout from keras.lay...
4,683
29.815789
90
py
hyperband
hyperband-master/defs_regression/meta.py
# meta regressor from common_defs import * regressors = ( 'gb', 'rf', 'xt', 'sgd', 'polylearn_fm', 'polylearn_pn', 'keras_mlp' ) # import all the functions for r in regressors: exec( "from defs_regression.{} import get_params as get_params_{}".format( r, r )) exec( "from defs_regression.{} import try_params as try_...
749
25.785714
85
py
SfSNet-PyTorch
SfSNet-PyTorch-master/main_gen_pseudo-data.py
# # Experiment Entry point # 1. Trains model on Syn Data # 2. Generates CelebA Data # 3. Trains on Syn + CelebA Data # import torch import torchvision from torchvision import transforms from torch.utils.data import DataLoader import matplotlib.pyplot as plt import torch.nn as nn import argparse import wandb from data...
6,117
41.783217
164
py
SfSNet-PyTorch
SfSNet-PyTorch-master/data_loading.py
import torch import torch.nn as nn from torch.utils.data import Dataset, DataLoader, random_split from torchvision import transforms import glob import cv2 from random import randint import os from skimage import io from PIL import Image import pandas as pd from utils import save_image, denorm, get_normal_in_range im...
10,618
32.498423
136
py
SfSNet-PyTorch
SfSNet-PyTorch-master/utils.py
import matplotlib.pyplot as plt import torchvision from PIL import Image from torch.nn import * def applyMask(input_img, mask): if mask is None: return input_img return input_img * mask def denorm(x): out = (x + 1) / 2 return out.clamp(0, 1) def get_normal_in_range(normal): new_normal = n...
1,681
26.57377
94
py
SfSNet-PyTorch
SfSNet-PyTorch-master/main_mix_training.py
# # Experiment Entry point # 1. Trains model on Syn Data # 2. Generates CelebA Data # 3. Trains on Syn + CelebA Data # import torch import torchvision from torchvision import transforms from torch.utils.data import DataLoader import matplotlib.pyplot as plt import torch.nn as nn import argparse import wandb from data...
4,960
40
164
py
SfSNet-PyTorch
SfSNet-PyTorch-master/main_gen_synthetic_and_full.py
# # Experiment Entry point # 1. Trains model on Syn Data # 2. Generates CelebA Data # 3. Trains on Syn + CelebA Data # import torch import torchvision from torchvision import transforms from torch.utils.data import DataLoader import matplotlib.pyplot as plt import torch.nn as nn import argparse import wandb from data...
6,749
41.993631
164
py
SfSNet-PyTorch
SfSNet-PyTorch-master/models.py
import torch import torch.nn as nn import torch.nn.functional as F from utils import denorm def get_shading(N, L): c1 = 0.8862269254527579 c2 = 1.0233267079464883 c3 = 0.24770795610037571 c4 = 0.8580855308097834 c5 = 0.4290427654048917 nx = N[:, 0, :, :] ny = N[:, 1, :, :] nz = N[:, 2...
31,228
50.279146
121
py
SfSNet-PyTorch
SfSNet-PyTorch-master/shading.py
import torch import torchvision import numpy as np import torch.nn as nn from torch.autograd import Variable from torchvision import transforms import pandas as pd from utils import * from models import sfsNetShading # def var(x): # if torch.cuda.is_available(): # x = x.cuda() # return Variable(x) # ...
5,090
36.160584
114
py
SfSNet-PyTorch
SfSNet-PyTorch-master/train.py
import torch import torch.nn as nn import numpy as np import os from models import * from utils import * from data_loading import * ## TODOS: ## 1. Dump SH in file ## ## ## Notes: ## 1. SH is not normalized ## 2. Face is normalized and denormalized - shall we not normalize in the first place? # Enable WANDB Loggi...
37,617
52.663338
213
py
SfSNet-PyTorch
SfSNet-PyTorch-master/interpolate.py
from models import * from utils import save_image from torch.utils.data import Dataset, DataLoader, random_split import torchvision from torchvision import transforms import numpy as np import os import argparse IMAGE_SIZE = 128 def interpolate(model_dir, input_path, output_path): use_cuda = torch.cuda.is_availab...
2,582
30.120482
89
py