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 |
|---|---|---|---|---|---|---|
eznlp | eznlp-master/eznlp/model/decoder/generator.py | # -*- coding: utf-8 -*-
from typing import List
import itertools
import nltk
import torch
from ...wrapper import Batch
from ...nn.modules import CombinedDropout, SequencePooling, SequenceAttention
from ...nn.modules import ConvBlock, TransformerDecoderBlock
from ...nn.init import reinit_layer_, reinit_lstm_, reinit_gr... | 31,922 | 47.295008 | 165 | py |
eznlp | eznlp-master/eznlp/model/decoder/span_classification.py | # -*- coding: utf-8 -*-
from collections import Counter
import logging
import math
import numpy
import torch
from ...wrapper import Batch
from ...utils.chunk import detect_overlapping_level, filter_clashed_by_priority
from ...nn.modules import SequencePooling, SequenceAttention, CombinedDropout, SoftLabelCrossEntropyL... | 10,770 | 50.535885 | 164 | py |
eznlp | eznlp-master/eznlp/model/decoder/boundary_selection.py | # -*- coding: utf-8 -*-
from typing import List
from collections import Counter
import logging
import math
import numpy
import torch
from ...wrapper import Batch
from ...utils.chunk import detect_overlapping_level, filter_clashed_by_priority
from ...nn.modules import CombinedDropout, SoftLabelCrossEntropyLoss
from ...... | 11,868 | 45.545098 | 170 | py |
eznlp | eznlp-master/eznlp/model/decoder/chunks.py | # -*- coding: utf-8 -*-
from typing import List, Union
import random
import torch
from ...wrapper import TargetWrapper
from .base import SingleDecoderConfigBase, DecoderBase
class ChunkPairs(TargetWrapper):
"""A wrapper of chunk-pairs with underlying relations.
This object enumerates all pairs between all p... | 9,419 | 50.47541 | 130 | py |
eznlp | eznlp-master/eznlp/model/decoder/specific_span_rel_classification.py | # -*- coding: utf-8 -*-
from typing import List, Dict
from collections import Counter
import logging
import math
import numpy
import torch
from ...wrapper import Batch
from ...nn.modules import CombinedDropout
from ...nn.init import reinit_embedding_, reinit_layer_
from ...metrics import precision_recall_f1_report
fro... | 14,022 | 47.522491 | 147 | py |
eznlp | eznlp-master/third_party/dice_loss_for_NLP/loss/dice_loss.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# file: dice_loss.py
# description:
# implementation of dice loss for NLP tasks.
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch import Tensor
from typing import Optional
class DiceLoss(nn.Module):
"""
Dice coefficient for short, i... | 7,805 | 40.521277 | 136 | py |
eznlp | eznlp-master/third_party/dice_loss_for_NLP/loss/focal_loss.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
from typing import List
import torch
import torch.nn as nn
import torch.nn.functional as F
class FocalLoss(nn.Module):
"""
Focal loss(https://arxiv.org/pdf/1708.02002.pdf)
Shape:
- input: (N, C)
- target: (N)
- Output: Scalar loss
... | 2,365 | 29.727273 | 85 | py |
eznlp | eznlp-master/scripts/joint_extraction.py | # -*- coding: utf-8 -*-
import os
import sys
import argparse
import datetime
import pdb
import logging
import pprint
import numpy
import torch
from eznlp import auto_device
from eznlp.dataset import Dataset
from eznlp.model import EncoderConfig
from eznlp.model import SequenceTaggingDecoderConfig, SpanClassificationDe... | 13,736 | 56.476987 | 214 | py |
eznlp | eznlp-master/scripts/text_classification.py | # -*- coding: utf-8 -*-
import os
import sys
import argparse
import datetime
import pdb
import logging
import pprint
import numpy
import torch
from eznlp import auto_device
from eznlp.token import TokenSequence
from eznlp.dataset import Dataset
from eznlp.config import ConfigDict
from eznlp.model import OneHotConfig, ... | 9,291 | 43.45933 | 152 | py |
eznlp | eznlp-master/scripts/entity_recognition.py | # -*- coding: utf-8 -*-
import os
import sys
import argparse
import datetime
import pdb
import logging
import pprint
import numpy
import torch
from eznlp import auto_device
from eznlp.token import LexiconTokenizer
from eznlp.nn.init import reinit_bert_like_
from eznlp.dataset import Dataset
from eznlp.config import Co... | 25,376 | 58.570423 | 211 | py |
eznlp | eznlp-master/scripts/pretraining.py | # -*- coding: utf-8 -*-
import os
import sys
import argparse
import datetime
import pdb
import glob
import logging
import pprint
import numpy
import torch
import transformers
from eznlp import auto_device
from eznlp.io import RawTextIO
from eznlp.dataset import PreTrainingDataset
from eznlp.plm import MaskedLMConfig
f... | 7,939 | 43.858757 | 162 | py |
eznlp | eznlp-master/scripts/utils.py | # -*- coding: utf-8 -*-
import os
import argparse
import logging
import re
import json
import spacy
import jieba
import random
import time
import numpy
import sklearn.model_selection
import torch
import allennlp.modules
import transformers
import flair
from eznlp.token import Full2Half
from eznlp.io import TabularIO, ... | 41,403 | 60.430267 | 220 | py |
eznlp | eznlp-master/scripts/image2text.py | # -*- coding: utf-8 -*-
import os
import sys
import argparse
import datetime
import pdb
import logging
import pprint
import numpy
import torch
import torchvision
from eznlp import auto_device
from eznlp.dataset import GenerationDataset
from eznlp.model import ImageEncoderConfig, OneHotConfig, GeneratorConfig
from eznl... | 8,902 | 48.73743 | 151 | py |
eznlp | eznlp-master/scripts/text2text.py | # -*- coding: utf-8 -*-
import os
import sys
import argparse
import datetime
import pdb
import logging
import pprint
import numpy
import torch
from eznlp import auto_device
from eznlp.dataset import GenerationDataset
from eznlp.model import OneHotConfig, EncoderConfig, GeneratorConfig
from eznlp.model import Text2Text... | 8,225 | 48.854545 | 155 | py |
eznlp | eznlp-master/scripts/relation_extraction.py | # -*- coding: utf-8 -*-
import os
import sys
import argparse
import datetime
import pdb
import logging
import pprint
import numpy
import torch
from eznlp import auto_device
from eznlp.dataset import Dataset
from eznlp.model import EncoderConfig
from eznlp.model import SpanRelClassificationDecoderConfig, SpecificSpanRe... | 11,460 | 53.837321 | 218 | py |
eznlp | eznlp-master/scripts/attribute_extraction.py | # -*- coding: utf-8 -*-
import os
import sys
import argparse
import datetime
import pdb
import logging
import pprint
import numpy
import torch
from eznlp import auto_device
from eznlp.dataset import Dataset
from eznlp.model import SpanAttrClassificationDecoderConfig
from eznlp.model import ExtractorConfig
from eznlp.t... | 7,211 | 44.358491 | 134 | py |
eznlp | eznlp-master/tests/test_dataset.py | # -*- coding: utf-8 -*-
import pytest
import torch
from eznlp.token import Token
from eznlp.dataset import Dataset
from eznlp.config import ConfigDict
from eznlp.model import OneHotConfig, MultiHotConfig, ExtractorConfig
def test_batch_to_cuda(conll2003_demo, device):
if device.type.startswith('cpu'):
py... | 1,755 | 38.022222 | 126 | py |
eznlp | eznlp-master/tests/conftest.py | # -*- coding: utf-8 -*-
import pytest
import spacy
import jieba
import torch
import torchvision
import allennlp.modules
import transformers
import flair
from eznlp import auto_device
from eznlp.token import TokenSequence
from eznlp.vectors import Vectors, GloVe
from eznlp.io import TabularIO, ConllIO, JsonIO, Karpathy... | 8,414 | 35.586957 | 114 | py |
eznlp | eznlp-master/tests/test_metrics.py | # -*- coding: utf-8 -*-
import pytest
import numpy
import nltk
import torchtext
from eznlp.metrics import precision_recall_f1_report
from eznlp.utils import ChunksTagsTranslator
from eznlp.io import ConllIO
class TestMetric(object):
def _assert_scores_equal(self, ave_scores, expected_ave_scores):
for key... | 3,618 | 50.7 | 105 | py |
eznlp | eznlp-master/tests/nn/test_aggregation.py | # -*- coding: utf-8 -*-
import pytest
import torch
from eznlp.nn.functional import seq_lens2mask
from eznlp.nn import SequencePooling, SequenceGroupAggregating
@pytest.mark.parametrize("mode, f_agg", [('mean', lambda x: x.mean(dim=0)),
('max', lambda x: x.max(dim=0).values)... | 3,297 | 39.219512 | 119 | py |
eznlp | eznlp-master/tests/nn/test_dropout.py | # -*- coding: utf-8 -*-
import pytest
import torch
from eznlp.nn import LockedDropout, WordDropout
@pytest.mark.parametrize("dropout_rate", [0.2, 0.5, 0.8])
def test_locked_dropout(dropout_rate):
BATCH_SIZE = 100
MAX_LEN = 200
HID_DIM = 500
x = torch.ones(BATCH_SIZE, MAX_LEN, HID_DIM)
dropou... | 1,296 | 29.162791 | 116 | py |
eznlp | eznlp-master/tests/nn/test_loss.py | # -*- coding: utf-8 -*-
import pytest
import torch
from eznlp.nn import SmoothLabelCrossEntropyLoss, FocalLoss
import third_party.dice_loss_for_NLP.loss
class TestFocalLoss(object):
@pytest.mark.parametrize("weight", [None, torch.tensor([0.1, 0.2, 0.3, 0.4, 0.5])])
@pytest.mark.parametrize("ignore_index", [-... | 6,282 | 45.198529 | 159 | py |
eznlp | eznlp-master/tests/nn/test_crf.py | # -*- coding: utf-8 -*-
import torch
import torchcrf
from eznlp.nn import CRF
def test_crf():
batch_size = 10
step = 20
tag_dim = 5
emissions = torch.randn(batch_size, step, tag_dim)
tag_ids = torch.randint(0, tag_dim, (batch_size, step))
seq_lens = torch.randint(1, step, (batch_size, ))
... | 1,101 | 34.548387 | 98 | py |
eznlp | eznlp-master/tests/nn/test_functional.py | # -*- coding: utf-8 -*-
import torch
from eznlp.nn.functional import seq_lens2mask, mask2seq_lens
def test_seq_lens2mask():
BATCH_SIZE = 100
MAX_LEN = 20
seq_lens = torch.randint(0, MAX_LEN, size=(BATCH_SIZE, )) + 1
mask = seq_lens2mask(seq_lens, max_len=MAX_LEN)
assert ((MAX_LEN - mask.sum(... | 592 | 27.238095 | 65 | py |
eznlp | eznlp-master/tests/nn/test_query_bert_like.py | # -*- coding: utf-8 -*-
import torch
from eznlp.nn.modules.query_bert_like import QueryBertLikeLayer, QueryBertLikeEncoder
def test_query_bert_like_layer(bert_like_with_tokenizer):
bert_like, tokenizer = bert_like_with_tokenizer
bert_layer = bert_like.encoder.layer[0]
query_bert_like_layer = QueryBertLik... | 1,376 | 42.03125 | 124 | py |
eznlp | eznlp-master/tests/nn/test_attention.py | # -*- coding: utf-8 -*-
import pytest
import torch
from eznlp.nn.functional import seq_lens2mask
from eznlp.nn import SequenceAttention
@pytest.mark.parametrize("num_heads", [1, 5])
@pytest.mark.parametrize("scoring", ['Dot', 'Scaled_Dot', 'Multiplicative', 'Additive', 'Biaffine'])
@pytest.mark.parametrize("nonlinea... | 1,021 | 36.851852 | 159 | py |
eznlp | eznlp-master/tests/io/test_src2trg.py | # -*- coding: utf-8 -*-
from eznlp.io import Src2TrgIO
class TestSrc2TrgIO(object):
def test_multi30k(self, spacy_nlp_en, spacy_nlp_de):
io = Src2TrgIO(tokenize_callback=spacy_nlp_de, trg_tokenize_callback=spacy_nlp_en, encoding='utf-8', case_mode='Lower', number_mode='None')
train_data = io.read(... | 3,139 | 52.220339 | 147 | py |
eznlp | eznlp-master/tests/training/test_trainer.py | # -*- coding: utf-8 -*-
import pytest
import random
import torch
from eznlp.dataset import Dataset
from eznlp.model import EncoderConfig, SequenceTaggingDecoderConfig, ExtractorConfig
from eznlp.training import Trainer
@pytest.mark.parametrize("use_amp", [False, True])
def test_train_steps(use_amp, conll2003_demo, d... | 2,854 | 45.803279 | 111 | py |
eznlp | eznlp-master/tests/plm/test_mlm.py | # -*- coding: utf-8 -*-
import pytest
import jieba
import torch
import transformers
from eznlp.io import RawTextIO
from eznlp.plm import MaskedLMConfig
from eznlp.dataset import PreTrainingDataset
from eznlp.training import MaskedLMTrainer
class TestMaskedLM(object):
def _assert_batch_consistency(self):
... | 4,329 | 47.111111 | 149 | py |
eznlp | eznlp-master/tests/model/test_flair.py | # -*- coding: utf-8 -*-
import pytest
import os
import torch
import flair
from eznlp.token import TokenSequence
from eznlp.model import FlairConfig
from eznlp.training import count_params
@pytest.mark.parametrize("agg_mode", ['last', 'mean'])
def test_flair_embeddings(agg_mode, flair_lm):
batch_tokenized_text = ... | 2,343 | 38.066667 | 123 | py |
eznlp | eznlp-master/tests/model/test_specific_span_classification.py | # -*- coding: utf-8 -*-
import pytest
import torch
from eznlp.dataset import Dataset
from eznlp.model import EncoderConfig
from eznlp.model import BertLikeConfig, SpanBertLikeConfig, SpecificSpanClsDecoderConfig, SpecificSpanExtractorConfig
from eznlp.model.bert_like import subtokenize_for_bert_like
from eznlp.trainin... | 8,291 | 64.291339 | 236 | py |
eznlp | eznlp-master/tests/model/test_text2text.py | # -*- coding: utf-8 -*-
import pytest
import torch
from eznlp.dataset import GenerationDataset
from eznlp.training import Trainer
from eznlp.model import OneHotConfig, EncoderConfig, GeneratorConfig, Text2TextConfig
class TestModel(object):
def _assert_batch_consistency(self):
self.model.eval()
... | 7,504 | 52.992806 | 165 | py |
eznlp | eznlp-master/tests/model/test_boundaries.py | # -*- coding: utf-8 -*-
import pytest
import torch
from eznlp.model import BoundarySelectionDecoderConfig, SpecificSpanRelClsDecoderConfig
from eznlp.model.decoder.boundaries import _spans_from_upper_triangular, _spans_from_diagonals, _span_pairs_from_diagonals
from eznlp.model.decoder.boundaries import _span2diagonal... | 9,914 | 60.583851 | 177 | py |
eznlp | eznlp-master/tests/model/test_joint_extraction.py | # -*- coding: utf-8 -*-
import pytest
import torch
from eznlp.dataset import Dataset
from eznlp.model import EncoderConfig, BertLikeConfig, SpanBertLikeConfig
from eznlp.model import SequenceTaggingDecoderConfig, BoundarySelectionDecoderConfig
from eznlp.model import SpanClassificationDecoderConfig, SpanAttrClassifica... | 8,368 | 55.931973 | 178 | py |
eznlp | eznlp-master/tests/model/test_image2text.py | # -*- coding: utf-8 -*-
import pytest
import torch
from eznlp.dataset import GenerationDataset
from eznlp.training import Trainer
from eznlp.model import ImageEncoderConfig, GeneratorConfig, Image2TextConfig
class TestModel(object):
def _assert_batch_consistency(self):
self.model.eval()
... | 5,233 | 44.12069 | 119 | py |
eznlp | eznlp-master/tests/model/test_bert_like.py | # -*- coding: utf-8 -*-
import pytest
import os
import string
import random
import numpy
import pandas
import torch
import transformers
from eznlp.token import TokenSequence
from eznlp.model import BertLikeConfig
from eznlp.model.bert_like import (truecase_for_bert_like,
truncate_fo... | 8,198 | 46.12069 | 167 | py |
eznlp | eznlp-master/tests/model/test_specific_span_rel_classification.py | # -*- coding: utf-8 -*-
import pytest
import torch
from eznlp.dataset import Dataset
from eznlp.model import EncoderConfig, BertLikeConfig, SpanBertLikeConfig
from eznlp.model import SpecificSpanRelClsDecoderConfig, SpecificSpanSparseRelClsDecoderConfig
from eznlp.model import SpecificSpanExtractorConfig
from eznlp.tr... | 5,786 | 54.114286 | 210 | py |
eznlp | eznlp-master/tests/model/test_span_attr_classification.py | # -*- coding: utf-8 -*-
import pytest
import torch
from eznlp.dataset import Dataset
from eznlp.model import BertLikeConfig, SpanAttrClassificationDecoderConfig, ExtractorConfig
from eznlp.training import Trainer
class TestModel(object):
def _assert_batch_consistency(self):
self.model.eval()
... | 3,726 | 43.369048 | 130 | py |
eznlp | eznlp-master/tests/model/test_elmo.py | # -*- coding: utf-8 -*-
import pytest
import os
import torch
from eznlp.model import ELMoConfig
from eznlp.training import count_params
@pytest.mark.parametrize("mix_layers", ['trainable', 'top', 'average'])
@pytest.mark.parametrize("use_gamma", [True, False])
@pytest.mark.parametrize("freeze", [True, False])
def te... | 1,112 | 30.8 | 98 | py |
eznlp | eznlp-master/tests/model/test_span_classification.py | # -*- coding: utf-8 -*-
import pytest
import torch
from eznlp.dataset import Dataset
from eznlp.model import EncoderConfig, BertLikeConfig, SpanClassificationDecoderConfig, ExtractorConfig
from eznlp.model.bert_like import subtokenize_for_bert_like
from eznlp.training import Trainer
class TestModel(object):
def ... | 3,986 | 45.360465 | 143 | py |
eznlp | eznlp-master/tests/model/test_boundary_selection.py | # -*- coding: utf-8 -*-
import pytest
import torch
from eznlp.dataset import Dataset
from eznlp.model import EncoderConfig, BertLikeConfig, BoundarySelectionDecoderConfig, ExtractorConfig
from eznlp.model.bert_like import subtokenize_for_bert_like
from eznlp.training import Trainer
class TestModel(object):
def _... | 5,376 | 50.701923 | 159 | py |
eznlp | eznlp-master/tests/model/test_span_bert_like.py | # -*- coding: utf-8 -*-
import pytest
import torch
from eznlp.model import SpanBertLikeConfig
from eznlp.training import count_params
def test_span_bert_like(bert_like_with_tokenizer):
bert_like, tokenizer = bert_like_with_tokenizer
config = SpanBertLikeConfig(bert_like=bert_like, max_span_size=5)
span_b... | 1,787 | 41.571429 | 146 | py |
eznlp | eznlp-master/tests/model/test_sequence_tagging.py | # -*- coding: utf-8 -*-
import pytest
import random
import torch
from eznlp.token import Token, LexiconTokenizer
from eznlp.dataset import Dataset
from eznlp.config import ConfigDict
from eznlp.model import OneHotConfig, MultiHotConfig, EncoderConfig
from eznlp.model import CharConfig, SoftLexiconConfig
from eznlp.mod... | 8,087 | 49.55 | 146 | py |
eznlp | eznlp-master/tests/model/test_text_classification.py | # -*- coding: utf-8 -*-
import pytest
import torch
from eznlp.dataset import Dataset
from eznlp.model import EncoderConfig, BertLikeConfig, TextClassificationDecoderConfig, ClassifierConfig
from eznlp.training import Trainer
class TestModel(object):
def _assert_batch_consistency(self):
self.model.eval()
... | 4,003 | 46.105882 | 140 | py |
eznlp | eznlp-master/tests/model/test_span_rel_classification.py | # -*- coding: utf-8 -*-
import pytest
import torch
from eznlp.dataset import Dataset
from eznlp.model import BertLikeConfig, SpanRelClassificationDecoderConfig, ExtractorConfig
from eznlp.training import Trainer
class TestModel(object):
def _assert_batch_consistency(self):
self.model.eval()
... | 3,823 | 43.988235 | 148 | py |
eznlp | eznlp-master/tests/model/test_nested_embedder.py | # -*- coding: utf-8 -*-
import pytest
import torch
from eznlp.token import LexiconTokenizer
from eznlp.model import EncoderConfig, NestedOneHotConfig, CharConfig, SoftLexiconConfig
class TestNestedOneHotEmbedder(object):
def _assert_batch_consistency(self):
self.embedder.eval()
seq_lens1... | 2,773 | 42.34375 | 90 | py |
flare | flare-master/ctests/test_nn.py | import ace
import nnp
import numpy as np
import torch
import copy
species = [6, 6, 6, 6, 6, 6, 6, 8, 8, 8, 6, 6, 8, 1, 1, 1, 1, 1, 1, 1, 1]
coded_species = []
for spec in species:
if spec == 6:
coded_species.append(0)
if spec == 8:
coded_species.append(1)
if spec == 1:
coded_specie... | 7,015 | 29.637555 | 75 | py |
SPINE | SPINE-master/code/model/main.py | import torch
from torch import nn
from torch.autograd import Variable
import argparse
import utils
from utils import DataHandler
from model import SPINEModel
from random import shuffle
import numpy as np
import logging
logging.basicConfig(level=logging.INFO)
#########################################################
... | 4,629 | 32.071429 | 117 | py |
SPINE | SPINE-master/code/model/model.py | import torch
from torch import nn
from torch.autograd import Variable
import logging
logging.basicConfig(level=logging.INFO)
class SPINEModel(torch.nn.Module):
def __init__(self, params):
super(SPINEModel, self).__init__()
# params
self.inp_dim = params['inp_dim']
self.hdim = params['hdim']
self.noise_... | 1,426 | 25.924528 | 86 | py |
rocket | rocket-master/.preprint/reproduce_experiments_scalability.py | # Angus Dempster, Francois Petitjean, Geoff Webb
# Dempster A, Petitjean F, Webb GI (2019) ROCKET: Exceptionally fast and
# accurate time series classification using random convolutional kernels.
# arXiv:1910.13051
import argparse
import numpy as np
import pandas as pd
import time
import torch, torch.nn as nn, torch.... | 12,747 | 40.796721 | 166 | py |
rocket | rocket-master/code/reproduce_experiments_scalability.py | # Angus Dempster, Francois Petitjean, Geoff Webb
#
# @article{dempster_etal_2020,
# author = {Dempster, Angus and Petitjean, Fran\c{c}ois and Webb, Geoffrey I},
# title = {ROCKET: Exceptionally fast and accurate time classification using random convolutional kernels},
# year = {2020},
# journal = {Data Mi... | 11,410 | 38.759582 | 166 | py |
particles | particles-master/docs/source/conf.py | # -*- coding: utf-8 -*-
#
# particles documentation build configuration file, created by
# sphinx-quickstart on Wed Feb 28 20:48:55 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
# autogenerated file.
#
#... | 9,675 | 31.361204 | 85 | py |
voxelmorph | voxelmorph-master/scripts/torch/register.py | #!/usr/bin/env python
"""
Example script to register two volumes with VoxelMorph models.
Please make sure to use trained models appropriately. Let's say we have a model trained to register a
scan (moving) to an atlas (fixed). To register a scan to the atlas and save the warp field, run:
register.py --moving movi... | 2,534 | 34.704225 | 126 | py |
voxelmorph | voxelmorph-master/scripts/torch/train.py | #!/usr/bin/env python
"""
Example script to train a VoxelMorph model.
For the CVPR and MICCAI papers, we have data arranged in train, validate, and test folders. Inside each folder
are normalized T1 volumes and segmentations in npz (numpy) format. You will have to customize this script slightly
to accommodate your ow... | 7,202 | 38.360656 | 143 | py |
voxelmorph | voxelmorph-master/scripts/tf/train_semisupervised_pointcloud.py | #!/usr/bin/env python
"""
Example script for training semi-supervised nonlinear registration aided by
surface point clouds generated from segmentations.
"""
import os
import random
import argparse
import glob
import numpy as np
import tensorflow as tf
import voxelmorph as vxm
# parse the commandline
parser = argpar... | 7,505 | 42.387283 | 146 | py |
voxelmorph | voxelmorph-master/scripts/tf/test.py | #!/usr/bin/env python
"""
Example script for testing quality of trained vxm models. This script iterates over a list of
images and corresponding segmentations, registers them to an atlas, propagates segmentations
to the atlas, and computes the dice overlap. Example usage is:
test.py \
--model models/model.h5 ... | 2,725 | 36.861111 | 116 | py |
voxelmorph | voxelmorph-master/scripts/tf/train_cond_template.py | #!/usr/bin/env python
"""
Example script to train conditional template creation. This code is still experimental
based on the experiments run in the preprint.
Learning Conditional Deformable Templates with Convolutional Networks
Adrian V. Dalca, Marianne Rakic, John Guttag, Mert R. Sabuncu
https://arxiv.org/abs/1908.... | 6,278 | 40.309211 | 159 | py |
voxelmorph | voxelmorph-master/scripts/tf/train_unsupervised_seg.py | #!/usr/bin/env python
"""
Trains a segmentation network in an unsupervised fashion, using a probabilistic
atlas and unlabeled scans.
Unsupervised deep learning for Bayesian brain MRI segmentation
A.V. Dalca, E. Yu, P. Golland, B. Fischl, M.R. Sabuncu, J.E. Iglesias
Under Review. arXiv https://arxiv.org/abs/1904.11319... | 5,624 | 38.0625 | 146 | py |
voxelmorph | voxelmorph-master/scripts/tf/test_unsupervised_seg.py | #!/usr/bin/env python
"""
Example script to test a segmentation network trained in an unsupervised fashion,
using a probabilistic atlas and unlabeled scans.
Unsupervised deep learning for Bayesian brain MRI segmentation
A.V. Dalca, E. Yu, P. Golland, B. Fischl, M.R. Sabuncu, J.E. Iglesias
Under Review. arXiv https://... | 6,442 | 39.522013 | 112 | py |
voxelmorph | voxelmorph-master/scripts/tf/train_synth_reg.py | #!/usr/bin/env python
"""
Example script to train a VoxelMorph model on images synthesized from segmentations.
"""
import sys
import os
import random
import argparse
import glob
import numpy as np
import tensorflow as tf
import voxelmorph as vxm
# parse the commandline
parser = argparse.ArgumentParser()
# data org... | 6,810 | 38.369942 | 146 | py |
voxelmorph | voxelmorph-master/scripts/tf/train_template.py | #!/usr/bin/env python
"""
Example script to train (unconditional) template creation.
"""
import os
import random
import argparse
import glob
import numpy as np
import tensorflow as tf
import voxelmorph as vxm
# parse the commandline
parser = argparse.ArgumentParser()
# data organization parameters
parser.add_argum... | 5,779 | 39.41958 | 146 | py |
voxelmorph | voxelmorph-master/scripts/tf/train_instance.py | #!/usr/bin/env python
"""
Instance-specific optimization
"""
import os
import argparse
import numpy as np
import voxelmorph as vxm
import tensorflow as tf
# parse the commandline
parser = argparse.ArgumentParser()
# data organization parameters
parser.add_argument('--moving', required=True, help='moving image (sou... | 3,850 | 37.51 | 127 | py |
voxelmorph | voxelmorph-master/scripts/tf/train_semisupervised_seg.py | #!/usr/bin/env python
"""
Example script to train a VoxelMorph model in a semi-supervised
fashion by providing ground-truth segmentation data for training images.
"""
import os
import random
import argparse
import glob
import numpy as np
import tensorflow as tf
import voxelmorph as vxm
# parse the commandline
parse... | 5,220 | 38.55303 | 123 | py |
voxelmorph | voxelmorph-master/scripts/tf/register.py | #!/usr/bin/env python
"""
Example script to register two volumes with VoxelMorph models.
Please make sure to use trained models appropriately. Let's say we have a model trained to register a
scan (moving) to an atlas (fixed). To register a scan to the atlas and save the warp field, run:
register.py --moving movi... | 2,126 | 38.388889 | 126 | py |
voxelmorph | voxelmorph-master/scripts/tf/train.py | #!/usr/bin/env python
"""
Example script to train a VoxelMorph model.
For the CVPR and MICCAI papers, we have data arranged in train, validate, and test folders. Inside each folder
are normalized T1 volumes and segmentations in npz (numpy) format. You will have to customize this script slightly
to accommodate your ow... | 6,581 | 41.464516 | 146 | py |
voxelmorph | voxelmorph-master/scripts/tf/warp.py | #!/usr/bin/env python
"""
Example script to apply a deformation to an image. Usage is:
warp.py --moving moving.nii.gz --warp warp.nii.gz --moved moved.nii.gz
Interpolation method can be specified with the --interp flag.
"""
import os
import argparse
import numpy as np
import voxelmorph as vxm
import tensorflow ... | 1,615 | 36.581395 | 134 | py |
voxelmorph | voxelmorph-master/voxelmorph/generators.py | import os
import sys
import glob
import numpy as np
from . import py
def volgen(
vol_names,
batch_size=1,
return_segs=False,
np_var='vol',
pad_shape=None,
resize_factor=1,
add_feat_axis=True
):
"""
Base generator for random volume loading. Volumes ... | 16,218 | 41.681579 | 165 | py |
voxelmorph | voxelmorph-master/voxelmorph/__init__.py | # ---- voxelmorph ----
# unsupervised learning for image registration
from . import generators
from . import py
from .py.utils import default_unet_features
# import backend-dependent submodules
backend = py.utils.get_backend()
if backend == 'pytorch':
# the pytorch backend can be enabled by setting the VXM_BACK... | 932 | 24.216216 | 85 | py |
voxelmorph | voxelmorph-master/voxelmorph/torch/modelio.py | import torch
import torch.nn as nn
import inspect
import functools
def store_config_args(func):
"""
Class-method decorator that saves every argument provided to the
function as a dictionary in 'self.config'. This is used to assist
model loading - see LoadableModel.
"""
attrs, varargs, varkw, ... | 2,686 | 33.896104 | 126 | py |
voxelmorph | voxelmorph-master/voxelmorph/torch/losses.py | import torch
import torch.nn.functional as F
import numpy as np
import math
class NCC:
"""
Local (over window) normalized cross correlation loss.
"""
def __init__(self, win=None):
self.win = win
def loss(self, y_true, y_pred):
I = y_true
J = y_pred
# get dimensi... | 3,146 | 25.669492 | 91 | py |
voxelmorph | voxelmorph-master/voxelmorph/torch/utils.py | import torch
| 13 | 6 | 12 | py |
voxelmorph | voxelmorph-master/voxelmorph/torch/networks.py | import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.distributions.normal import Normal
from .. import default_unet_features
from . import layers
from .modelio import LoadableModel, store_config_args
class Unet(nn.Module):
"""
A unet architecture. Layer features can be specified dire... | 8,875 | 37.094421 | 115 | py |
voxelmorph | voxelmorph-master/voxelmorph/torch/layers.py | import torch
import torch.nn as nn
import torch.nn.functional as nnf
class SpatialTransformer(nn.Module):
"""
N-D Spatial Transformer
"""
def __init__(self, size, mode='bilinear'):
super().__init__()
self.mode = mode
# create sampling grid
vectors = [torch.arange(0, ... | 3,192 | 31.581633 | 96 | py |
voxelmorph | voxelmorph-master/voxelmorph/py/utils.py | # internal python imports
import os
import csv
import functools
# third party imports
import numpy as np
import scipy
from skimage import measure
# local/our imports
import pystrum.pynd.ndutils as nd
def default_unet_features():
nb_features = [
[16, 32, 32, 32], # encoder
[32, 32, 32... | 12,701 | 30.994962 | 116 | py |
voxelmorph | voxelmorph-master/voxelmorph/tf/modelio.py | import tensorflow as tf
import h5py
import json
import inspect
import functools
def store_config_args(func):
"""
Class-method decorator that saves every argument provided to the
function as a dictionary in 'self.config'. This is used to assist
model loading - see LoadableModel.
"""
attrs, var... | 4,168 | 32.620968 | 126 | py |
voxelmorph | voxelmorph-master/voxelmorph/tf/losses.py | import sys
import numpy as np
import tensorflow as tf
import tensorflow.keras.layers as KL
import tensorflow.keras.backend as K
class NCC:
"""
Local (over window) normalized cross correlation loss.
"""
def __init__(self, win=None, eps=1e-5):
self.win = win
self.eps = eps
def ncc(... | 14,730 | 35.017115 | 151 | py |
voxelmorph | voxelmorph-master/voxelmorph/tf/utils.py | """
tensorflow/keras utilities for voxelmorph
If you use this code, please cite one of the voxelmorph papers:
https://github.com/voxelmorph/voxelmorph/blob/master/citations.bib
Contact: adalca [at] csail [dot] mit [dot] edu
License: GPLv3
"""
# internal python imports
import os
# third party imports
import numpy as... | 15,284 | 34.964706 | 108 | py |
voxelmorph | voxelmorph-master/voxelmorph/tf/networks.py | """
tensorflow/keras networks for voxelmorph
If you use this code, please cite one of the voxelmorph papers:
https://github.com/voxelmorph/voxelmorph/blob/master/citations.bib
License: GPLv3
"""
# internal python imports
from collections.abc import Iterable
# third party imports
import numpy as np
import tensorflow... | 42,824 | 44.174051 | 148 | py |
voxelmorph | voxelmorph-master/voxelmorph/tf/layers.py | """
tensorflow/keras layers for voxelmorph
If you use this code, please cite one of the voxelmorph papers:
https://github.com/voxelmorph/voxelmorph/blob/master/citations.bib
License: GPLv3
"""
# internal python imports
import os
# third party
import numpy as np
import tensorflow as tf
from tensorflow import keras ... | 22,484 | 35.501623 | 119 | py |
voxelmorph | voxelmorph-master/voxelmorph/tf/synthseg/labels_to_image_model.py | import tensorflow.keras as keras
import numpy as np
import tensorflow as tf
import tensorflow.keras.layers as KL
import tensorflow.keras.backend as K
import numpy.random as npr
# from sklearn import preprocessing
from neurite import layers as nrn_layers
from .utils import add_axis, gauss_kernel, format_target_res, get... | 19,632 | 61.525478 | 125 | py |
DDA | DDA-master/adaptive_inference.py | from __future__ import absolute_import
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import division
import torch
import torch.nn as nn
import os
import math
import numpy as np
np.set_printoptions(threshold=np.inf)
def dynamic_evaluate(model, classifier, test_loader, ... | 7,292 | 37.384211 | 79 | py |
DDA | DDA-master/network.py | import numpy as np
import torch
import torch.nn as nn
from torchvision import models
import math
def calc_coeff(iter_num, high=1.0, low=0.0, alpha=10.0, max_iter=10000.0):
return np.float(2.0 * (high - low) /
(1.0 + np.exp(-alpha * iter_num / max_iter)) -
(high - low) + low... | 15,531 | 32.259101 | 118 | py |
DDA | DDA-master/loss.py | import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
def Entropy(input_):
# bs = input_.size(0)
epsilon = 1e-5
entropy = -input_ * torch.log(input_ + epsilon)
entropy = torch.sum(entropy, dim=1)
return entropy
def grl_hook(coeff):
def fun1(grad):
retu... | 1,105 | 25.333333 | 73 | py |
DDA | DDA-master/op_counter.py | from __future__ import absolute_import
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import division
import torch
from torch.autograd import Variable
from functools import reduce
import operator
'''
Calculate the FLOPS of each exit without lazy prediction pruning"
''... | 4,457 | 29.326531 | 80 | py |
DDA | DDA-master/data_list.py | import torch
import numpy as np
import random
from PIL import Image
from torch.utils.data import Dataset
import os
import os.path
import heapq
def make_dataset(image_list, labels):
if labels:
len_ = len(image_list)
images = [(image_list[i].strip(), labels[i, :]) for i in range(len_)]
else:
... | 3,738 | 28.210938 | 77 | py |
DDA | DDA-master/msdnet.py | import math
import torch
import torch.nn as nn
# ---- GradientRescale ---- #
class GradientRescaleFunction(torch.autograd.Function):
@staticmethod
def forward(ctx, input, weight):
ctx.save_for_backward(input)
ctx.gd_scale_weight = weight
output = input
return output
@stati... | 15,022 | 34.265258 | 93 | py |
DDA | DDA-master/pre_process.py | import numpy as np
from torchvision import transforms
import os
from PIL import Image, ImageOps
import random
import numbers
import torch
class ResizeImage():
def __init__(self, size):
if isinstance(size, int):
self.size = (int(size), int(size))
else:
self.size = size
... | 7,666 | 31.214286 | 83 | py |
DDA | DDA-master/distance.py | import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
def MeanCosDistance(feature):
cls_size = len(feature)
mean = feature[0].clone()
for i in range(cls_size):
if i != 0:
mean += feature[i]
distance = torch.cosine_similarity(mean, feature[0], dim=1)... | 1,812 | 21.109756 | 79 | py |
DDA | DDA-master/train_dda.py | import argparse
import os
import os.path as osp
import datetime
import torch
import torch.nn as nn
import torch.optim as optim
import numpy as np
import lr_schedule
import distance
import pre_process as prep
from torch.utils.data import DataLoader
from data_list import ImageList
from data_list import MinHeap
import ms... | 35,160 | 41.058612 | 80 | py |
RE3 | RE3-master/dreamer_re3/dreamer.py | import argparse
import collections
import functools
import json
import os
import pathlib
import sys
import time
os.environ["TF_CPP_MIN_LOG_LEVEL"] = "3"
os.environ["MUJOCO_GL"] = "egl"
import numpy as np
import tensorflow as tf
from tensorflow.keras.mixed_precision import experimental as prec
tf.get_logger().setLeve... | 21,362 | 37.631103 | 100 | py |
RE3 | RE3-master/dreamer_re3/tools.py | import datetime
import io
import pathlib
import pickle
import re
import uuid
import gym
import numpy as np
import tensorflow as tf
import tensorflow.compat.v1 as tf1
import tensorflow_probability as tfp
from tensorflow.keras.mixed_precision import experimental as prec
from tensorflow_probability import distributions a... | 15,413 | 31.726115 | 84 | py |
RE3 | RE3-master/dreamer_re3/models.py | import numpy as np
import tensorflow as tf
from tensorflow.keras import layers as tfkl
from tensorflow_probability import distributions as tfd
from tensorflow.keras.mixed_precision import experimental as prec
import tools
class RSSM(tools.Module):
def __init__(self, stoch=30, deter=200, hidden=200, act=tf.nn.elu... | 9,928 | 37.785156 | 82 | py |
RE3 | RE3-master/a2c_re3/torch-ac/setup.py | from setuptools import setup, find_packages
setup(
name="torch_ac",
version="1.1.0",
keywords="reinforcement learning, actor-critic, a2c, ppo, multi-processes, gpu",
packages=find_packages(),
install_requires=[
"numpy>=1.13.0",
"torch>=1.0.0"
]
)
| 288 | 21.230769 | 84 | py |
RE3 | RE3-master/a2c_re3/torch-ac/torch_ac/format.py | import torch
def default_preprocess_obss(obss, device=None):
return torch.tensor(obss, device=device) | 106 | 25.75 | 47 | py |
RE3 | RE3-master/a2c_re3/torch-ac/torch_ac/model.py | from abc import abstractmethod, abstractproperty
import torch.nn as nn
import torch.nn.functional as F
class ACModel:
recurrent = False
@abstractmethod
def __init__(self, obs_space, action_space):
pass
@abstractmethod
def forward(self, obs):
pass
class RecurrentACModel(ACModel):
... | 485 | 17.692308 | 48 | py |
RE3 | RE3-master/a2c_re3/torch-ac/torch_ac/__init__.py | from torch_ac.algos import A2CAlgo, PPOAlgo
from torch_ac.model import ACModel, RecurrentACModel
from torch_ac.utils import DictList | 132 | 43.333333 | 52 | py |
RE3 | RE3-master/a2c_re3/torch-ac/torch_ac/algos/base.py | from abc import ABC, abstractmethod
import torch
from torch_ac.format import default_preprocess_obss
from torch_ac.utils import DictList, ParallelEnv
import torch.nn as nn
import numpy as np
from skimage.util.shape import view_as_windows
def weight_init(m):
"""Custom weight init for Conv2D and Linear layers."""... | 14,308 | 38.527624 | 110 | py |
RE3 | RE3-master/a2c_re3/torch-ac/torch_ac/algos/a2c.py | from itertools import chain
import numpy
import torch
import torch.nn.functional as F
from torch_ac.algos.base import BaseAlgo
class A2CAlgo(BaseAlgo):
"""The Advantage Actor-Critic algorithm."""
def __init__(self, envs, acmodel, device=None, num_frames_per_proc=None, discount=0.99, lr=0.01, gae_lambda=0.95,... | 4,912 | 34.345324 | 124 | py |
RE3 | RE3-master/a2c_re3/torch-ac/torch_ac/algos/ppo.py | import numpy
import torch
import torch.nn.functional as F
from torch_ac.algos.base import BaseAlgo
class PPOAlgo(BaseAlgo):
"""The Proximal Policy Optimization algorithm
([Schulman et al., 2015](https://arxiv.org/abs/1707.06347))."""
def __init__(self, envs, acmodel, device=None, num_frames_per_proc=None... | 6,011 | 37.538462 | 118 | py |
RE3 | RE3-master/a2c_re3/torch-ac/torch_ac/algos/__init__.py | from torch_ac.algos.a2c import A2CAlgo
from torch_ac.algos.ppo import PPOAlgo | 77 | 38 | 38 | py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.