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 |
|---|---|---|---|---|---|---|
espnet | espnet-master/egs2/librispeech/ssl1/local/measure_teacher_quality.py | # The measure_teacher_quality.py uses code from Fairseq:
# https://github.com/pytorch/fairseq/blob/master/examples/hubert/measure_teacher_quality.py
#
# Thanks to Abdelrahman Mohamed and Wei-Ning Hsu's help in this implementation,
# Their origial Hubert work is in:
# Paper: https://arxiv.org/pdf/2106.07447.pdf
... | 6,713 | 26.292683 | 95 | py |
espnet | espnet-master/egs2/slurp_spatialized/asr1/local/multi_to_single.py | import os
import sys
from multiprocessing import Pool
from pathlib import Path
import torchaudio
import tqdm
multi_path = sys.argv[1]
single_path = sys.argv[2]
data_list = ["tr_real", "tr_synthetic", "cv", "tt", "tt_qut"]
def m2s(pf):
if ".wav" not in pf[2]:
return
mwav = os.path.join(pf[0], pf[2])... | 1,386 | 26.74 | 83 | py |
espnet | espnet-master/egs2/chime7_task1/diar_asr1/local/pyannote_diarize.py | import argparse
import glob
import json
import math
import os.path
import re
from pathlib import Path
import numpy as np
import soundfile as sf
import torch
from pyannote.audio import Model, Pipeline
from pyannote.audio.core.inference import Inference
from pyannote.audio.pipelines import SpeakerDiarization
from pyanno... | 14,818 | 32.603175 | 87 | py |
espnet | espnet-master/egs2/chime7_task1/diar_asr1/local/pyannote_finetune.py | import argparse
import os.path
import shutil
from pathlib import Path
from types import MethodType
from pyannote.audio import Inference, Model
from pyannote.audio.tasks import Segmentation
from pyannote.database import FileFinder, get_protocol
from pytorch_lightning import Trainer
from pytorch_lightning.callbacks impo... | 5,429 | 27.429319 | 87 | py |
espnet | espnet-master/egs2/chime7_task1/asr1/local/gss_micrank.py | import argparse
import os
from copy import deepcopy
from pathlib import Path
import lhotse
import soundfile as sf
import torch
import torchaudio
import tqdm
from torch.utils.data import DataLoader, Dataset
class EnvelopeVariance(torch.nn.Module):
"""
Envelope Variance Channel Selection method with
(optio... | 8,190 | 33.707627 | 87 | py |
FixMatch-pytorch | FixMatch-pytorch-master/train.py | import argparse
import logging
import math
import os
import random
import shutil
import time
from collections import OrderedDict
import numpy as np
import torch
import torch.nn.functional as F
import torch.optim as optim
from torch.optim.lr_scheduler import LambdaLR
from torch.utils.data import DataLoader, RandomSampl... | 19,677 | 38.199203 | 238 | py |
FixMatch-pytorch | FixMatch-pytorch-master/dataset/cifar.py | import logging
import math
import numpy as np
from PIL import Image
from torchvision import datasets
from torchvision import transforms
from .randaugment import RandAugmentMC
logger = logging.getLogger(__name__)
cifar10_mean = (0.4914, 0.4822, 0.4465)
cifar10_std = (0.2471, 0.2435, 0.2616)
cifar100_mean = (0.5071, ... | 6,239 | 33.098361 | 87 | py |
FixMatch-pytorch | FixMatch-pytorch-master/dataset/randaugment.py | # code in this file is adpated from
# https://github.com/ildoonet/pytorch-randaugment/blob/master/RandAugment/augmentations.py
# https://github.com/google-research/fixmatch/blob/master/third_party/auto_augment/augmentations.py
# https://github.com/google-research/fixmatch/blob/master/libml/ctaugment.py
import logging
i... | 5,821 | 25.343891 | 99 | py |
FixMatch-pytorch | FixMatch-pytorch-master/models/resnext.py | import logging
import torch
import torch.nn as nn
import torch.nn.functional as F
logger = logging.getLogger(__name__)
def mish(x):
"""Mish: A Self Regularized Non-Monotonic Neural Activation Function (https://arxiv.org/abs/1908.08681)"""
return x * torch.tanh(F.softplus(x))
class nn.BatchNorm2d(nn.BatchN... | 7,390 | 41.97093 | 112 | py |
FixMatch-pytorch | FixMatch-pytorch-master/models/ema.py | from copy import deepcopy
import torch
class ModelEMA(object):
def __init__(self, args, model, decay):
self.ema = deepcopy(model)
self.ema.to(args.device)
self.ema.eval()
self.decay = decay
self.ema_has_module = hasattr(self.ema, 'module')
# Fix EMA. https://github... | 1,297 | 32.282051 | 78 | py |
FixMatch-pytorch | FixMatch-pytorch-master/models/wideresnet.py | import logging
import torch
import torch.nn as nn
import torch.nn.functional as F
logger = logging.getLogger(__name__)
def mish(x):
"""Mish: A Self Regularized Non-Monotonic Neural Activation Function (https://arxiv.org/abs/1908.08681)"""
return x * torch.tanh(F.softplus(x))
class PSBatchNorm2d(nn.BatchNo... | 5,338 | 41.373016 | 119 | py |
FixMatch-pytorch | FixMatch-pytorch-master/utils/misc.py | '''Some helper functions for PyTorch, including:
- get_mean_and_std: calculate the mean and std value of dataset.
'''
import logging
import torch
logger = logging.getLogger(__name__)
__all__ = ['get_mean_and_std', 'accuracy', 'AverageMeter']
def get_mean_and_std(dataset):
'''Compute the mean and std value ... | 1,726 | 25.569231 | 95 | py |
Deep-xVA-Solver | Deep-xVA-Solver-master/basketCallWithCVA.py | import numpy as np
import matplotlib.pyplot as plt
import tensorflow as tf
import xvaEquation as eqn
from solver import BSDESolver
from XvaSolver import XvaSolver
import RecursiveEquation as receqn
import munch
import pandas as pd
if __name__ == "__main__":
dim = 100 #dimension of brownian motion
P = 2048 #... | 4,627 | 35.440945 | 91 | py |
Deep-xVA-Solver | Deep-xVA-Solver-master/callOption.py | import numpy as np
import matplotlib.pyplot as plt
import tensorflow as tf
from solver import BSDESolver
import xvaEquation as eqn
import munch
import pandas as pd
if __name__ == "__main__":
dim = 1 #dimension of brownian motion
P = 2048 #number of outer Monte Carlo Loops
batch_size = 64
total_time ... | 2,853 | 32.186047 | 87 | py |
Deep-xVA-Solver | Deep-xVA-Solver-master/fvaForward.py | import numpy as np
import matplotlib.pyplot as plt
import tensorflow as tf
from solver import BSDESolver
from XvaSolver import XvaSolver
import xvaEquation as eqn
import RecursiveEquation as receqn
import munch
from scipy.stats import norm
if __name__ == "__main__":
dim = 1 #dimension of brownian motion
P =... | 5,069 | 33.726027 | 91 | py |
Deep-xVA-Solver | Deep-xVA-Solver-master/XvaSolver.py | import logging
import time
import numpy as np
import tensorflow as tf
from tqdm import tqdm
import tensorflow.keras.layers as layers
DELTA_CLIP = 50.0
class XvaSolver(object):
"""The fully connected neural network model."""
def __init__(self, config, bsde):
self.eqn_config = config.eqn_config
... | 10,030 | 43.982063 | 130 | py |
Deep-xVA-Solver | Deep-xVA-Solver-master/basketCall.py | import numpy as np
import matplotlib.pyplot as plt
import tensorflow as tf
from solver import BSDESolver
import xvaEquation as eqn
import munch
import pandas as pd
if __name__ == "__main__":
dim = 100 #dimension of brownian motion
P = 2048 #number of outer Monte Carlo Loops
batch_size = 64
total_tim... | 3,193 | 33.717391 | 87 | py |
Deep-xVA-Solver | Deep-xVA-Solver-master/solver.py | import logging
import time
import numpy as np
import tensorflow as tf
from tqdm import tqdm
import tensorflow.keras.layers as layers
DELTA_CLIP = 50.0
class BSDESolver(object):
"""The fully connected neural network model."""
def __init__(self, config, bsde):
self.eqn_config = config.eqn_config
... | 9,986 | 43.584821 | 156 | py |
Deep-xVA-Solver | Deep-xVA-Solver-master/forward.py | import numpy as np
import matplotlib.pyplot as plt
import tensorflow as tf
from solver import BSDESolver
import xvaEquation as eqn
import munch
from scipy.stats import norm
import pandas as pd
if __name__ == "__main__":
dim = 1 #dimension of brownian motion
P = 2048 #number of outer Monte Carlo Loops
ba... | 3,107 | 33.153846 | 88 | py |
Deep-xVA-Solver | Deep-xVA-Solver-master/callOptionStabilityTests.py | import numpy as np
import matplotlib.pyplot as plt
import tensorflow as tf
from solver import BSDESolver
import xvaEquation as eqn
import munch
import pandas as pd
if __name__ == "__main__":
dim = 1 #dimension of brownian motion
P = 2048 #number of outer Monte Carlo Loops
batch_size = 64
total_time ... | 2,953 | 32.954023 | 116 | py |
inferno | inferno-master/setup.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""The setup script."""
from setuptools import setup, find_packages
import runpy
__version__ = runpy.run_path('inferno/version.py')['__version__']
with open('README.rst') as readme_file:
readme = readme_file.read()
with open('HISTORY.rst') as history_file:
hist... | 2,255 | 27.556962 | 116 | py |
inferno | inferno-master/examples/regularized_mnist.py | """
Regularized MNIST Example
================================
This example demonstrates adding and logging arbitrary regularization losses, in this case,
L2 activity regularization and L1 weight regularization.
- Add a `_losses` dictionary to any module containing loss names and values
- Use a criterion from `infern... | 4,545 | 35.368 | 103 | py |
inferno | inferno-master/examples/plot_cheap_unet.py | """
UNet Tutorial
================================
A unet example which can be run without a gpu
"""
##############################################################################
# Preface
# --------------
# We start with some unspectacular multi purpose imports needed for this example
import matplotlib.pyplot as plt... | 8,435 | 33.859504 | 144 | py |
inferno | inferno-master/examples/plot_unet_tutorial.py | """
UNet Tutorial
================================
A tentative tutorial on the usage
of the unet framework in inferno
"""
##############################################################################
# Preface
# --------------
# We start with some unspectacular multi purpose imports needed for this example
import mat... | 9,582 | 35.299242 | 107 | py |
inferno | inferno-master/examples/plot_train_side_loss_unet.py | """
Train Side Loss UNet Example
================================
In this example a UNet with side supervision
and auxiliary loss implemented
"""
##############################################################################
# Imports needed for this example
import torch
import torch.nn as nn
from inferno.io.box.bi... | 7,112 | 30.613333 | 104 | py |
inferno | inferno-master/examples/trainer.py | """
Trainer Example
================================
This example should illustrate how to use the trainer class.
"""
import torch.nn as nn
from inferno.io.box.cifar import get_cifar10_loaders
from inferno.trainers.basic import Trainer
from inferno.trainers.callbacks.logging.tensorboard import TensorboardLogger
from... | 2,399 | 30.578947 | 76 | py |
inferno | inferno-master/inferno/io/core/base.py | from torch.utils.data.dataset import Dataset
class SyncableDataset(Dataset):
def __init__(self, base_sequence=None):
self.base_sequence = base_sequence
def sync_with(self, dataset):
if hasattr(dataset, 'base_sequence'):
self.base_sequence = dataset.base_sequence
return sel... | 1,170 | 33.441176 | 91 | py |
inferno | inferno-master/inferno/io/core/zip.py | from torch.utils.data.dataset import Dataset
import torch.multiprocessing as mp
import numpy as np
from . import data_utils as du
from .base import SyncableDataset
from ...utils.exceptions import assert_
from ...utils import python_utils as pyu
import random
class Zip(SyncableDataset):
"""
Zip two or more dat... | 10,048 | 45.308756 | 107 | py |
inferno | inferno-master/inferno/io/core/concatenate.py | import numpy as np
from torch.utils.data.dataset import Dataset
from ...utils import python_utils as pyu
class Concatenate(Dataset):
"""
Concatenates mutliple datasets to one. This class does not implement
synchronization primitives.
"""
def __init__(self, *datasets, transforms=None):
asse... | 2,559 | 40.290323 | 95 | py |
inferno | inferno-master/inferno/io/box/cityscapes.py | import zipfile
import io
import os
import torch.utils.data as data
from PIL import Image
from os.path import join, relpath, abspath
from ...utils.exceptions import assert_
from ..transform.base import Compose
from ..transform.generic import \
Normalize, NormalizeRange, Cast, AsTorchBatch, Project, Label2OneHot
from... | 12,804 | 33.146667 | 98 | py |
inferno | inferno-master/inferno/io/box/camvid.py | # Adapted from felixgwu's PR here:
# https://github.com/felixgwu/vision/blob/cf491d301f62ae9c77ff7250fb7def5cd55ec963/torchvision/datasets/camvid.py
import os
import torch
import torch.utils.data as data
import numpy as np
from PIL import Image
from torchvision.datasets.folder import default_loader
from ...utils.excep... | 8,776 | 38.714932 | 113 | py |
inferno | inferno-master/inferno/io/box/binary_blobs.py | import torch.utils.data as data
import skimage.data
import numpy
from operator import mul
from functools import reduce
class BinaryBlobs(data.Dataset):
def __init__(self, size=20, length=512, blob_size_fraction=0.1,
n_dim=2, volume_fraction=0.5,split='train',
uniform_noise_rang... | 5,580 | 37.226027 | 101 | py |
inferno | inferno-master/inferno/io/box/cifar.py | import os
import torch
import torchvision
import torchvision.transforms as transforms
from torch.utils.data.sampler import SubsetRandomSampler
def get_cifar10_loaders(root_directory, train_batch_size=128, test_batch_size=256,
download=False, augment=False, validation_dataset_size=None):
# ... | 6,337 | 52.260504 | 96 | py |
inferno | inferno-master/inferno/io/transform/image.py | import numpy as np
from scipy.ndimage import zoom
from scipy.ndimage.filters import gaussian_filter
from scipy.ndimage.interpolation import map_coordinates, rotate
from scipy.ndimage.morphology import binary_dilation, binary_erosion
from skimage.exposure import adjust_gamma
from warnings import catch_warnings, simplefi... | 26,648 | 43.341098 | 107 | py |
inferno | inferno-master/inferno/io/transform/volume.py | import numpy as np
import scipy
from scipy.ndimage import zoom
from scipy.ndimage.morphology import binary_dilation, binary_erosion
from .base import Transform
from ...utils.exceptions import assert_
class RandomFlip3D(Transform):
def __init__(self, **super_kwargs):
super(RandomFlip3D, self).__init__(**su... | 16,485 | 41.380463 | 99 | py |
inferno | inferno-master/inferno/io/transform/generic.py | import numpy as np
import torch
from .base import Transform, DTypeMapping
from ...utils.exceptions import assert_, DTypeError
class Normalize(Transform):
"""Normalizes input to zero mean unit variance."""
def __init__(self, eps=1e-4, mean=None, std=None, ignore_value=None, **super_kwargs):
"""
... | 8,277 | 39.578431 | 97 | py |
inferno | inferno-master/inferno/extensions/initializers/base.py | import torch.nn.init as init
__all__ = ['Initializer',
'Initialization',
'WeightInitFunction',
'BiasInitFunction',
'TensorInitFunction']
class Initializer(object):
"""
Base class for all initializers.
"""
# TODO Support LSTMs and GRUs
VALID_LAYERS = {... | 4,904 | 36.159091 | 96 | py |
inferno | inferno-master/inferno/extensions/initializers/presets.py | import numpy as np
import torch.nn.init as init
from functools import partial
from .base import Initialization, Initializer
__all__ = ['Constant', 'NormalWeights',
'SELUWeightsZeroBias',
'ELUWeightsZeroBias',
'OrthogonalWeightsZeroBias',
'KaimingNormalWeightsZeroBias']
c... | 2,751 | 32.560976 | 97 | py |
inferno | inferno-master/inferno/extensions/models/unet.py | import torch
import torch.nn as nn
from ..layers.identity import Identity
from ..layers.convolutional import ConvELU2D, ConvELU3D, Conv2D, Conv3D
from ..layers.sampling import Upsample as InfernoUpsample
from ...utils.math_utils import max_allowed_ds_steps
__all__ = ['UNetBase', 'UNet', 'ResBlockUNet']
_all = __all__... | 14,315 | 36.37859 | 104 | py |
inferno | inferno-master/inferno/extensions/models/res_unet.py | import torch
import torch.nn as nn
from ..layers.convolutional import ConvActivation
from .unet import UNetBase
from ...utils.python_utils import require_dict_kwargs
__all__ = ['ResBlockUNet']
_all = __all__
# We only use this for the u-net implementation here
# in favor of less code duplication it might be a
# goo... | 8,404 | 39.408654 | 103 | py |
inferno | inferno-master/inferno/extensions/metrics/categorical.py | import torch
from .base import Metric
from ...utils.torch_utils import flatten_samples, is_label_tensor
from ...utils.exceptions import assert_, DTypeError, ShapeError
class CategoricalError(Metric):
"""Categorical error."""
def __init__(self, aggregation_mode='mean'):
assert aggregation_mode in ['mea... | 6,159 | 44.294118 | 94 | py |
inferno | inferno-master/inferno/extensions/containers/graph.py | from collections import OrderedDict
import sys
import threading
import multiprocessing as mp
import copy
import gc
import networkx as nx
from networkx import is_directed_acyclic_graph, topological_sort
from torch import nn as nn
from ...utils import python_utils as pyu
from ...utils.exceptions import assert_
from ..l... | 18,135 | 37.020964 | 99 | py |
inferno | inferno-master/inferno/extensions/containers/sequential.py | import torch.nn as nn
from ...utils import python_utils as pyu
__all__ = ['Sequential1', 'Sequential2']
class Sequential1(nn.Sequential):
"""Like torch.nn.Sequential, but with a few extra methods."""
def __len__(self):
return len(self._modules.values())
class Sequential2(Sequential1):
"""Anoth... | 658 | 27.652174 | 90 | py |
inferno | inferno-master/inferno/extensions/layers/identity.py | import torch.nn as nn
__all__ = ['identity']
_all = __all__
class Identity(nn.Module):
def __init__(self):
super(Identity, self).__init__()
def forward(self, x):
return x | 198 | 18.9 | 40 | py |
inferno | inferno-master/inferno/extensions/layers/convolutional.py | import torch.nn as nn
import sys
import functools
from ..initializers import (
OrthogonalWeightsZeroBias,
KaimingNormalWeightsZeroBias,
SELUWeightsZeroBias,
)
from ..initializers import Initializer
from .normalization import BatchNormND
from .activations import SELU
from ...utils.exceptions import assert_, ... | 10,967 | 32.439024 | 114 | py |
inferno | inferno-master/inferno/extensions/layers/convolutional_blocks.py | import torch.nn as nn
from .convolutional import BNReLUConv2D, BNReLUDeconv2D, Conv2D, Deconv2D
from ...utils import python_utils as pyu
from ...utils.exceptions import assert_
__all__ = ['ResidualBlock', 'PreActSimpleResidualBlock']
_all = __all__
class ResidualBlock(nn.Module):
def __init__(self, layers, resam... | 2,616 | 41.901639 | 93 | py |
inferno | inferno-master/inferno/extensions/layers/reshape.py | import torch
import torch.nn as nn
import torch.nn.functional as F
from ...utils.exceptions import assert_, ShapeError
from ...utils import python_utils as pyu
__all__ = ['View', 'AsMatrix', 'Flatten',
'As3D', 'As2D',
'Concatenate', 'Cat',
'ResizeAndConcatenate', 'PoolCat',
... | 8,186 | 34.137339 | 124 | py |
inferno | inferno-master/inferno/extensions/layers/sampling.py | import torch.nn as nn
__all__ = ['AnisotropicUpsample', 'AnisotropicPool', 'Upsample', 'AnisotropicUpsample2D', 'AnisotropicPool2D']
# torch is deprecating nn.Upsample in favor of nn.functional.interpolate
# we wrap interpolate here to still use Upsample as class
class Upsample(nn.Module):
def __init__(self, siz... | 3,269 | 37.470588 | 110 | py |
inferno | inferno-master/inferno/extensions/layers/activations.py | import torch.nn.functional as F
import torch.nn as nn
from ...utils.torch_utils import where
__all__ = ['SELU']
_all = __all__
class SELU(nn.Module):
def forward(self, input):
return self.selu(input)
@staticmethod
def selu(x):
alpha = 1.6732632423543772848170429916717
scale = 1.05... | 444 | 25.176471 | 57 | py |
inferno | inferno-master/inferno/extensions/layers/normalization.py | import torch.nn as nn
class BatchNormND(nn.Module):
def __init__(self, dim, num_features,
eps=1e-5, momentum=0.1,
affine=True,track_running_stats=True):
super(BatchNormND, self).__init__()
assert dim in [1, 2, 3]
self.bn = getattr(nn, 'BatchNorm{}d'.form... | 504 | 35.071429 | 95 | py |
inferno | inferno-master/inferno/extensions/layers/device.py | import torch.nn as nn
from ...utils.python_utils import from_iterable, to_iterable
from ...utils.exceptions import assert_, DeviceError
__all__ = ['DeviceTransfer', 'OnDevice']
_all = __all__
class DeviceTransfer(nn.Module):
"""Layer to transfer variables to a specified device."""
def __init__(self, target_d... | 3,792 | 38.103093 | 90 | py |
inferno | inferno-master/inferno/extensions/criteria/core.py | import torch.nn as nn
from functools import reduce
from ...utils.exceptions import assert_, ShapeError, NotTorchModuleError
__all__ = ['Criteria', 'As2DCriterion']
class Criteria(nn.Module):
"""Aggregate multiple criteria to one."""
def __init__(self, *criteria):
super(Criteria, self).__init__()
... | 3,139 | 42.013699 | 96 | py |
inferno | inferno-master/inferno/extensions/criteria/set_similarity_measures.py | import torch.nn as nn
from ...utils.torch_utils import flatten_samples
__all__ = ['SorensenDiceLoss', 'GeneralizedDiceLoss']
class SorensenDiceLoss(nn.Module):
"""
Computes a loss scalar, which when minimized maximizes the Sorensen-Dice similarity
between the input and the target. For both inputs and tar... | 6,051 | 42.228571 | 117 | py |
inferno | inferno-master/inferno/extensions/criteria/elementwise_measures.py | import torch.nn as nn
from ...utils.exceptions import assert_
class WeightedMSELoss(nn.Module):
NEGATIVE_CLASS_WEIGHT = 1.
def __init__(self, positive_class_weight=1., positive_class_value=1., size_average=True):
super(WeightedMSELoss, self).__init__()
assert_(positive_class_weight >= 0,
... | 1,434 | 46.833333 | 94 | py |
inferno | inferno-master/inferno/extensions/criteria/regularized.py | import warnings
import torch
from torch import nn
from . import set_similarity_measures, core
__all__ = [
'RegularizedLoss',
'RegularizedCrossEntropyLoss',
'RegularizedBCEWithLogitsLoss',
'RegularizedBCELoss',
'RegularizedMSELoss',
'RegularizedNLLLoss'
]
def collect_losses(module):
"""C... | 4,589 | 33 | 107 | py |
inferno | inferno-master/inferno/extensions/optimizers/adam.py | import math
from torch.optim import Optimizer
class Adam(Optimizer):
"""Implements Adam algorithm with the option of adding a L1 penalty.
It has been proposed in `Adam: A Method for Stochastic Optimization`_.
Arguments:
params (iterable): iterable of parameters to optimize or dicts defining
... | 3,106 | 37.8375 | 88 | py |
inferno | inferno-master/inferno/utils/model_utils.py | import torch
from .exceptions import assert_, NotTorchModuleError, ShapeError
def is_model_cuda(model):
try:
return next(model.parameters()).is_cuda
except StopIteration:
# Assuming that if a network has no parameters, it doesn't use CUDA
return False
class ModelTester(object):
d... | 2,688 | 37.971014 | 101 | py |
inferno | inferno-master/inferno/utils/train_utils.py | """Utilities for training."""
import numpy as np
from .exceptions import assert_, FrequencyTypeError, FrequencyValueError
class AverageMeter(object):
"""
Computes and stores the average and current value.
Taken from https://github.com/pytorch/examples/blob/master/imagenet/main.py
"""
def __init__(... | 9,484 | 31.934028 | 98 | py |
inferno | inferno-master/inferno/utils/torch_utils.py | import numpy as np
import torch
from .python_utils import delayed_keyboard_interrupt
from .exceptions import assert_, ShapeError, NotUnwrappableError
def unwrap(input_, to_cpu=True, as_numpy=False, extract_item=False):
if isinstance(input_, (list, tuple)):
return type(input_)([unwrap(_t, to_cpu=to_cpu, a... | 4,749 | 30.045752 | 97 | py |
inferno | inferno-master/inferno/utils/test_utils.py | import torch
from torch.utils.data.dataset import TensorDataset
from torch.utils.data.dataloader import DataLoader
import numpy as np
def generate_random_data(num_samples, shape, num_classes, hardness=0.3, dtype=None):
"""Generate a random dataset with a given hardness and number of classes."""
dataset_input ... | 1,901 | 50.405405 | 93 | py |
inferno | inferno-master/inferno/trainers/basic.py | from datetime import datetime
from inspect import signature
import os
import shutil
# These are fetched from globals, they're not unused
# noinspection PyUnresolvedReferences
import dill
# noinspection PyUnresolvedReferences
import pickle
import torch
from numpy import inf
from torch.utils.data import DataLoader
fro... | 72,802 | 38.848385 | 114 | py |
inferno | inferno-master/inferno/trainers/callbacks/essentials.py | import numpy as np
import os
import h5py as h5
from ...utils import torch_utils as tu
from ...utils.train_utils import Frequency
from ...utils.exceptions import assert_, FrequencyValueError, NotUnwrappableError
from ...utils import python_utils as pyu
from .base import Callback
import gc
class NaNDetector(Callback):
... | 12,316 | 41.619377 | 100 | py |
inferno | inferno-master/inferno/trainers/callbacks/logging/tensorboard.py | import warnings
import numpy as np
from torch.utils.tensorboard import SummaryWriter
from .base import Logger
from ....utils import torch_utils as tu
from ....utils import python_utils as pyu
from ....utils import train_utils as tru
from ....utils.exceptions import assert_
class TaggedImage(object):
def __init__... | 20,981 | 45.215859 | 113 | py |
inferno | inferno-master/tests/test_inferno.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Tests for `inferno` package."""
import unittest
import numpy as np
import torch
import os
import shutil
from os.path import dirname, join
from torch.utils.data.dataset import TensorDataset
from torch.utils.data.dataloader import DataLoader
from inferno.extensions.laye... | 6,088 | 41.880282 | 93 | py |
inferno | inferno-master/tests/test_io/test_box/test_camvid.py | import os
from os.path import join, dirname, exists, isdir
import unittest
import numpy as np
_CAMVID_ROOT = None
def _camvid_available():
return _CAMVID_ROOT is not None or os.environ.get('CAMVID_ROOT') is not None
class TestCamvid(unittest.TestCase):
CAMVID_ROOT = _CAMVID_ROOT
PLOT_DIRECTORY = join(... | 5,616 | 45.421488 | 99 | py |
inferno | inferno-master/tests/test_io/test_box/test_cityscapes.py | import os
from os.path import join, dirname, exists, isdir
import unittest
import numpy as np
import time
_CITYSCAPES_ROOT = None
def _cityscapes_available():
return _CITYSCAPES_ROOT is not None or os.environ.get('CITYSCAPES_ROOT') is not None
class TestCityscapes(unittest.TestCase):
CITYSCAPES_ROOT = _CIT... | 5,462 | 45.29661 | 106 | py |
inferno | inferno-master/tests/test_io/test_core/test_zip.py | import unittest
class ZipTest(unittest.TestCase):
def test_zip_minimal(self):
"""Minimal test with python lists as iterators."""
from inferno.io.core import Zip
from torch.utils.data.dataset import Dataset
with self.assertRaises(TypeError):
zipped = Zip([1, 2, 3], [4, ... | 2,058 | 31.68254 | 87 | py |
inferno | inferno-master/tests/test_io/test_core/test_concatenate.py | import unittest
class ConcatenateTest(unittest.TestCase):
def test_concatenate(self):
from inferno.io.core import Concatenate
from torch.utils.data.dataset import Dataset
with self.assertRaises(AssertionError):
cated = Concatenate([1, 2, 3], [4, 5, 6, 7])
class ListDa... | 945 | 26.823529 | 60 | py |
inferno | inferno-master/tests/test_utils/test_partial_cls.py | import unittest
import inferno.utils.model_utils as mu
from inferno.utils.partial_cls import register_partial_cls
import torch
import torch.nn as nn
class TestCls(object):
def __init__(self, a, b, c=1, d=2):
self.a = a
self.b = b
self.c = c
self.d = d
class PartialClsTester(unitte... | 3,316 | 23.036232 | 58 | py |
inferno | inferno-master/tests/test_utils/test_model_utils.py | import unittest
import inferno.utils.model_utils as mu
from inferno.utils.exceptions import ShapeError
import torch
import torch.nn as nn
class ModelUtilTester(unittest.TestCase):
def test_model_tester(self):
model = mu.ModelTester((1, 10, 32, 32), (1, 20, 32, 32))(nn.Conv2d(10, 20, 3, padding=1))
... | 832 | 35.217391 | 97 | py |
inferno | inferno-master/tests/test_training/test_basic.py | from unittest import TestCase, skipUnless
import torch
from unittest import main
import time
from os.path import join, dirname
class TestTrainer(TestCase):
# Parameters
ROOT_DIR = dirname(__file__)
CUDA = False
HALF_PRECISION = False
DOWNLOAD_CIFAR = True
@staticmethod
def _make_test_mode... | 7,264 | 37.036649 | 100 | py |
inferno | inferno-master/tests/test_training/test_callbacks/test_essentials.py | import unittest
import shutil
import h5py as h5
from os.path import dirname, join
from os import listdir
from inferno.trainers.basic import Trainer
from inferno.trainers.callbacks.essentials import DumpHDF5Every
from inferno.utils.test_utils import generate_random_dataloader
from inferno.extensions.layers import Conv2D... | 3,964 | 44.574713 | 97 | py |
inferno | inferno-master/tests/test_training/test_callbacks/test_scheduling.py | import unittest
from inferno.trainers.callbacks.scheduling import ManualLR
from torch import nn
from torch.optim import Adam
class TestSchedulers(unittest.TestCase):
def test_manual_lr(self):
class DummyTrainer(object):
def __init__(self):
self.iteration_count = 0
... | 1,256 | 34.914286 | 76 | py |
inferno | inferno-master/tests/test_training/test_callbacks/test_base.py | import unittest
import torch
from inferno.trainers.callbacks.base import Callback, CallbackEngine
from inferno.trainers.basic import Trainer
from os.path import join, dirname, exists
from os import makedirs
from shutil import rmtree
class DummyCallback(Callback):
def end_of_training_iteration(self, **_):
... | 2,391 | 32.222222 | 80 | py |
inferno | inferno-master/tests/test_training/test_callbacks/test_logging/test_tensorboard.py | import unittest
import os
from shutil import rmtree
import numpy as np
import torch
import torch.nn as nn
from inferno.trainers.basic import Trainer
from torch.utils.data.dataset import TensorDataset
from torch.utils.data.dataloader import DataLoader
from inferno.trainers.callbacks.logging.tensorboard import Tensorboa... | 3,992 | 38.147059 | 94 | py |
inferno | inferno-master/tests/test_extensions/test_layers/test_device.py | import unittest
from inferno.extensions.layers.device import DeviceTransfer, OnDevice
import torch
class TransferTest(unittest.TestCase):
@unittest.skipIf(not torch.cuda.is_available(), "GPU not available.")
def test_device_transfer(self):
if not torch.cuda.is_available():
return
#... | 1,215 | 32.777778 | 91 | py |
inferno | inferno-master/tests/test_extensions/test_layers/test_reshape.py | import unittest
import torch
class TestReshape(unittest.TestCase):
def _get_input_variable(self, *shape):
return torch.rand(*shape)
def test_as_matrix(self):
from inferno.extensions.layers.reshape import AsMatrix
input = self._get_input_variable(10, 20, 1, 1)
as_matrix = AsMa... | 2,420 | 34.086957 | 81 | py |
inferno | inferno-master/tests/test_extensions/test_layers/test_activations.py | import unittest
import torch
import inferno.extensions.layers.activations as activations
class ActivationTest(unittest.TestCase):
def test_selu(self):
x = torch.rand(100)
y = activations.SELU()(x)
self.assertEqual(list(x.size()), list(y.size()))
if __name__ == '__main__':
unittest.ma... | 325 | 20.733333 | 59 | py |
inferno | inferno-master/tests/test_extensions/test_layers/test_convolutional.py | import unittest
import torch
from inferno.utils.model_utils import ModelTester
class TestConvolutional(unittest.TestCase):
@unittest.skipIf(not torch.cuda.is_available(), "GPU not available.")
def test_bn_relu_depthwise_conv2d_pyinn(self):
from inferno.extensions.layers.convolutional import BNReLUDept... | 615 | 31.421053 | 81 | py |
inferno | inferno-master/tests/test_extensions/test_layers/deprecated/building_blocks.py | import unittest
import torch
import inferno.extensions.layers.building_blocks as bb
class ResBlockTest(unittest.TestCase):
def test_2D_simple_(self):
x = torch.rand(1, 3, 64, 15)
model = bb.ResBlock(in_channels=3, out_channels=3, dim=2)
xx = model(x)
out_size = xx.size()
... | 2,372 | 29.037975 | 90 | py |
inferno | inferno-master/tests/test_extensions/test_containers/test_graph.py | import unittest
from functools import reduce
import torch
class TestGraph(unittest.TestCase):
def setUp(self):
import torch.nn as nn
from inferno.utils.python_utils import from_iterable
class DummyNamedModule(nn.Module):
def __init__(self, name, history, num_inputs=1):
... | 5,288 | 37.05036 | 82 | py |
inferno | inferno-master/tests/test_extensions/test_models/test_unet.py | import unittest
import torch.cuda as cuda
from inferno.utils.model_utils import ModelTester, MultiscaleModelTester
from inferno.extensions.models import UNet
class _MultiscaleUNet(UNet):
def conv_op_factory(self, in_channels, out_channels, part, index):
return super(_MultiscaleUNet, self).conv_op_factory(i... | 2,199 | 36.288136 | 114 | py |
inferno | inferno-master/tests/test_extensions/test_models/test_res_unet.py | import unittest
import torch
import torch.cuda as cuda
from inferno.utils.model_utils import ModelTester
class ResUNetTest(unittest.TestCase):
def test_res_unet_2d(self):
from inferno.extensions.models import ResBlockUNet
tester = ModelTester((1, 1, 256, 256), (1, 1, 256, 256))
if cuda.is_... | 3,023 | 35 | 68 | py |
inferno | inferno-master/tests/test_extensions/test_criteria/test_core.py | import unittest
import torch
import torch.nn as nn
class TestCore(unittest.TestCase):
def test_as_2d_criterion(self):
from inferno.extensions.criteria.core import As2DCriterion
prediction = torch.FloatTensor(2, 10, 100, 100).uniform_()
prediction = nn.Softmax2d()(prediction)
targe... | 507 | 25.736842 | 66 | py |
inferno | inferno-master/tests/test_extensions/test_criteria/test_elementwise_measures.py | import unittest
import inferno.extensions.criteria.elementwise_measures as em
import torch
class TestElementwiseMeasures(unittest.TestCase):
def test_weighted_mse_loss(self):
input = torch.zeros(10, 10)
target = torch.ones(10, 10)
loss = em.WeightedMSELoss(positive_class_weight=2.)(input, ... | 644 | 31.25 | 74 | py |
inferno | inferno-master/tests/test_extensions/test_criteria/test_set_similarity_measures.py | import unittest
import torch
class SetSimilarityTest(unittest.TestCase):
def get_dummy_variables(self):
x = torch.zeros(3, 2, 100, 100).uniform_()
y = torch.zeros(3, 2, 100, 100).uniform_()
return x, y
def get_dummy_variables_with_channels_and_classes(self):
# (batch_size, cha... | 1,999 | 37.461538 | 91 | py |
inferno | inferno-master/tests/test_extensions/test_metrics/categorical.py | import unittest
import torch
from inferno.extensions.metrics import IOU
class TestCategorical(unittest.TestCase):
def test_iou_basic(self):
# from one hot
predicted_image = torch.zeros(*(2, 10, 10))
predicted_image[:, 0:4, 0:4] = 1
target_image = torch.zeros(*(2, 10, 10))
t... | 2,048 | 39.176471 | 87 | py |
inferno | inferno-master/docs/conf.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# inferno documentation build configuration file, created by
# sphinx-quickstart on Tue Jul 9 22:26:36 2013.
#
# 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
# aut... | 10,920 | 28.357527 | 111 | py |
building-inspection-toolkit | building-inspection-toolkit-master/setup.py | import setuptools
with open("README.md", "r") as file:
long_description = file.read()
#with open("requirements.txt") as file:
# required = file.read().splitlines()
setuptools.setup(
name="building-inspection-toolkit",
version="0.3.0",
author="Philipp J. Roesch, Johannes Flotzinger",
author... | 1,319 | 29 | 73 | py |
building-inspection-toolkit | building-inspection-toolkit-master/tests/test_codebrim.py | #!/usr/local/bin/python3
# Test Modules
import sys
import pytest
from torchvision import transforms
from os import path, makedirs
import torch
import numpy as np
from PIL import Image
from pathlib import Path
import os
# Import module under test
# sys.path.append(path.dirname(path.dirname(path.abspath(__file__))))
fr... | 2,869 | 37.266667 | 149 | py |
building-inspection-toolkit | building-inspection-toolkit-master/tests/test_mcds.py | #!/usr/local/bin/python3
# Test Modules
import sys
import pytest
from os import path, makedirs
import torch
import numpy as np
from PIL import Image
from pathlib import Path
from torchvision import transforms
import os
# Import module under test
# sys.path.append(path.dirname(path.dirname(path.abspath(__file__))))
fr... | 4,476 | 34.816 | 116 | py |
building-inspection-toolkit | building-inspection-toolkit-master/tests/test_sdnet.py | #!/usr/local/bin/python3
# Test Modules
import sys
import pytest
from torchvision import transforms
from os import path, makedirs
import torch
import numpy as np
from PIL import Image
from pathlib import Path
import os
# Import module under test
# sys.path.append(path.dirname(path.dirname(path.abspath(__file__))))
fr... | 2,883 | 35.506329 | 122 | py |
building-inspection-toolkit | building-inspection-toolkit-master/tests/test_bcd.py | #!/usr/local/bin/python3
# Test Modules
import sys
import pytest
from torchvision import transforms
from os import path, makedirs
import torch
import numpy as np
from PIL import Image
from pathlib import Path
import os
# Import module under test
# sys.path.append(path.dirname(path.dirname(path.abspath(__file__))))
fr... | 2,493 | 35.144928 | 122 | py |
building-inspection-toolkit | building-inspection-toolkit-master/tests/test_cds.py | #!/usr/local/bin/python3
# Test Modules
import sys
import pytest
from torchvision import transforms
from os import path, makedirs
import torch
import numpy as np
from PIL import Image
from pathlib import Path
import os
# Import module under test
# sys.path.append(path.dirname(path.dirname(path.abspath(__file__))))
fr... | 2,498 | 34.7 | 119 | py |
building-inspection-toolkit | building-inspection-toolkit-master/bikit/utils.py | import gdown
import os
import hashlib
import zipfile
import json
import pprint
from os.path import dirname
from PIL import Image
from urllib.request import urlretrieve
from time import sleep
import requests
import cv2
import requests
from io import BytesIO
import torch
pp = pprint.PrettyPrinter(indent=4)
bikit_path =... | 8,465 | 37.307692 | 132 | py |
building-inspection-toolkit | building-inspection-toolkit-master/bikit/datasets.py | import torch
from torch.utils.data import Dataset
import pandas as pd
import numpy as np
import json
import os
import PIL
from PIL import Image
from torchvision import transforms
from os.path import dirname
from bikit.utils import pil_loader, cv2_loader, DATASETS
from pathlib import Path
from tqdm import tqdm
class B... | 5,624 | 42.945313 | 130 | py |
building-inspection-toolkit | building-inspection-toolkit-master/bikit/models.py | import numpy as np
import torch
from torch import nn
from torchvision import models
from efficientnet_pytorch import EfficientNet
from efficientnet_pytorch.utils import MemoryEfficientSwish
import time
from PIL import Image
import matplotlib.pyplot as plt
import json
from pathlib import Path
import sys
# Dict to fin... | 9,120 | 41.226852 | 152 | py |
building-inspection-toolkit | building-inspection-toolkit-master/bikit/metrics.py | import torch
from torchmetrics import Metric
from torchmetrics import Recall
class EMR_mt(Metric):
def __init__(self, use_logits=True, dist_sync_on_step=False):
super().__init__(dist_sync_on_step=dist_sync_on_step)
self.use_logits = use_logits
self.add_state("correct", default=torch.tensor... | 2,124 | 32.203125 | 80 | py |
Hierarchical-Localization | Hierarchical-Localization-master/hloc/extract_features.py | import argparse
import torch
from pathlib import Path
from typing import Dict, List, Union, Optional
import h5py
from types import SimpleNamespace
import cv2
import numpy as np
from tqdm import tqdm
import pprint
import collections.abc as collections
import PIL.Image
import glob
from . import extractors, logger
from .... | 10,549 | 32.814103 | 79 | py |
Hierarchical-Localization | Hierarchical-Localization-master/hloc/pairs_from_retrieval.py | import argparse
from pathlib import Path
from typing import Optional
import h5py
import numpy as np
import torch
import collections.abc as collections
from . import logger
from .utils.parsers import parse_image_lists
from .utils.read_write_model import read_images_binary
from .utils.io import list_h5_names
def parse... | 4,649 | 36.804878 | 79 | py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.