repo
stringlengths
2
99
file
stringlengths
13
225
code
stringlengths
0
18.3M
file_length
int64
0
18.3M
avg_line_length
float64
0
1.36M
max_line_length
int64
0
4.26M
extension_type
stringclasses
1 value
flaxformer
flaxformer-main/flaxformer/t5x/configs/moe/__init__.py
0
0
0
py
flaxformer
flaxformer-main/flaxformer/t5x/configs/calm/gin_configs_test.py
# Copyright 2023 Google LLC. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
4,936
32.134228
79
py
flaxformer
flaxformer-main/flaxformer/t5x/configs/calm/__init__.py
0
0
0
py
flaxformer
flaxformer-main/flaxformer/t5x/configs/t5/gin_configs_test.py
# Copyright 2023 Google LLC. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
4,841
31.496644
79
py
flaxformer
flaxformer-main/flaxformer/t5x/configs/t5/__init__.py
0
0
0
py
flaxformer
flaxformer-main/flaxformer/t5x/configs/longt5/gin_configs_test.py
# Copyright 2023 Google LLC. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
6,865
34.210256
79
py
flaxformer
flaxformer-main/flaxformer/t5x/configs/longt5/__init__.py
0
0
0
py
pytket
pytket-main/examples/spambench.py
### Script for benchmarking different SPAM correction methods. from collections import Counter from random import seed, random, randrange from time import perf_counter from pytket.circuit import Node, Bit # type: ignore from pytket.utils.spam import SpamCorrecter from pytket.backends.backendresult import BackendResul...
4,180
24.968944
113
py
pytket
pytket-main/examples/creating_backends_exercise.py
from pytket.circuit import OpType, Qubit, Bit, UnitID from pytket.pauli import Pauli, QubitPauliString from binarytree import Node from typing import List, Optional, Iterator, Dict, Set, Tuple from copy import copy import numpy as np class Gate: """Top-level class for Gates. Handles the shared behaviour for ...
21,732
41.282101
115
py
pytket
pytket-main/examples/oxfordQIS.py
## EXAMPLE FILE FOR THE OXFORD QIS WORKSHOP FROM 22 FEB 2020 ## THIS IS WRITTEN TO WORK WITH PYTKET v0.4.1 AND WILL NOT BE UPDATED IN FUTURE from pytket.circuit import Circuit, PauliExpBox, Pauli from pytket.predicates import CompilationUnit from pytket.passes import DecomposeBoxes, PauliSimp, SequencePass from pytket...
6,560
36.278409
462
py
pytket
pytket-main/examples/python/conditional_gate_example.py
# # Conditional Execution # Whilst any quantum process can be created by performing "pure" operations delaying all measurements to the end, this is not always practical and can greatly increase the resource requirements. It is much more convenient to alternate quantum gates and measurements, especially if we can use t...
5,107
41.92437
575
py
pytket
pytket-main/examples/python/spam_example.py
# # Calibration and Correction of State Preparation and Measurement (SPAM) # Quantum Computers available in the NISQ-era are limited by significant sources of device noise which cause errors in computation. One such noise source is errors in the preparation and measurement of quantum states, more commonly know as SPAM...
8,107
48.139394
470
py
pytket
pytket-main/examples/python/circuit_generation_example.py
# # Circuit generation: tket example # This notebook will provide a brief introduction to some of the more advanced methods of circuit generation available in `pytket`, including: # * how to address wires and registers; # * reading in circuits from QASM and Quipper ASCII files; # * various types of 'boxes'; # * compos...
11,156
30.877143
427
py
pytket
pytket-main/examples/python/creating_backends.py
# # How to create your own `Backend` using `pytket` # In this tutorial, we will focus on: # - the components of the abstract `Backend` class; # - adaptations for statevector simulation versus measurement sampling. # To run this example, you will only need the core `pytket` package. # # The `pytket` framework currentl...
34,346
43.147815
655
py
pytket
pytket-main/examples/python/pytket-qujax-classification.py
from jax import numpy as jnp, random, vmap, value_and_grad, jit from pytket import Circuit from pytket.circuit.display import render_circuit_jupyter from pytket.extensions.qujax import tk_to_qujax import qujax import matplotlib.pyplot as plt # # Define the classification task # We'll try and learn a _donut_ binary cla...
5,758
37.393333
328
py
pytket
pytket-main/examples/python/ansatz_sequence_example.py
# # Ansatz Sequencing: tket example # When performing variational algorithms like VQE, one common approach to generating circuit ansätze is to take an operator $U$ representing excitations and use this to act on a reference state $\lvert \phi_0 \rangle$. One such ansatz is the Unitary Coupled Cluster ansatz. Each exci...
7,424
64.707965
782
py
pytket
pytket-main/examples/python/backends_example.py
# # Backends: tket example # This example shows how to use `pytket` to execute quantum circuits on both simulators and real devices, and how to interpret the results. As tket is designed to be platform-agnostic, we have unified the interfaces of different providers as much as possible into the `Backend` class for maxi...
16,076
62.545455
594
py
pytket
pytket-main/examples/python/measurement_reduction_example.py
# # Advanced Expectation Values and Measurement Reduction # This notebook is an advanced follow-up to the "expectation_value_example" notebook, focussing on reducing the number of circuits required for measurement. # # When calculating the expectation value $\langle \psi \vert H \vert \psi \rangle$ of some operator $H...
6,625
67.309278
839
py
pytket
pytket-main/examples/python/contextual_optimization.py
# # Contextual optimisation # This notebook will illustrate the techniques of "contextual optimisation" available in TKET. # See the user manaul for an introduction to the concept and methods. Here we will present an example showing how we can save some gates at the beginnning and end of a circuit, making no assumpti...
2,911
40.6
298
py
pytket
pytket-main/examples/python/expectation_value_example.py
# # Expectation Values # Given a circuit generating a quantum state $\lvert \psi \rangle$, it is very common to have an operator $H$ and ask for the expectation value $\langle \psi \vert H \vert \psi \rangle$. A notable example is in quantum computational chemistry, where $\lvert \psi \rangle$ encodes the wavefunction...
13,903
53.3125
569
py
pytket
pytket-main/examples/python/comparing_simulators.py
# # Comparison of the simulators available through tket # In this tutorial, we will focus on: # - exploring the wide array of simulators available through the extension modules for `pytket`; # - comparing their unique features and capabilities. # This example assumes the reader is familiar with the basics of circuit ...
11,216
38.083624
541
py
pytket
pytket-main/examples/python/circuit_analysis_example.py
# # Circuit analysis: tket example # This notebook will introduce the basic methods of analysis and visualization of circuits available in `pytket`. # # It makes use of the modules `pytket_qiskit` and `pytket_cirq` for visualization; these need to be installed (with `pip`) in addition to `pytket`. # # We'll start by g...
3,903
33.548673
368
py
pytket
pytket-main/examples/python/Forest_portability_example.py
# # Code Portability and Intro to Forest # The quantum hardware landscape is incredibly competitive and rapidly changing. Many full-stack quantum software platforms lock users into them in order to use the associated devices and simulators. This notebook demonstrates how `pytket` can free up your existing high-level c...
5,440
55.677083
511
py
pytket
pytket-main/examples/python/qiskit_integration.py
# # Integrating `pytket` into Qiskit software # In this tutorial, we will focus on: # - Using `pytket` for compilation or providing devices/simulators within Qiskit workflows; # - Adapting Qiskit code to use `pytket` directly. # This example assumes some familiarity with the Qiskit algorithms library. We have chosen ...
5,151
61.072289
552
py
pytket
pytket-main/examples/python/symbolics_example.py
# # Symbolic compilation: tket example # Motivation: in compilation, particularly of hybrid classical-quantum variational algorithms in which the structure of a circuit remains constant but the parameters of some gates change, it can be useful to compile using symbolic parameters and optimise the circuit without knowl...
3,543
44.435897
367
py
pytket
pytket-main/examples/python/entanglement_swapping.py
# # Iterated Entanglement Swapping using tket # In this tutorial, we will focus on: # - designing circuits with mid-circuit measurement and conditional gates; # - utilising noise models in supported simulators. # This example assumes the reader is familiar with the Qubit Teleportation and Entanglement Swapping protoc...
15,313
41.303867
596
py
pytket
pytket-main/examples/python/pytket-qujax_qaoa.py
# # Symbolic circuits with `qujax` and `pytket-qujax` # In this notebook we will show how to manipulate symbolic circuits with the `pytket-qujax` extension. In particular, we will consider a QAOA and an Ising Hamiltonian. from pytket import Circuit from pytket.circuit.display import render_circuit_jupyter from jax imp...
6,609
47.962963
478
py
pytket
pytket-main/examples/python/compilation_example.py
# # Compilation passes: tket example # There are numerous ways to optimize circuits in `pytket`. In this notebook we will introduce the basics of compilation passes and how to combine and apply them. # # We assume familiarity with the `pytket` `Circuit` class. The objective is to transform one `Circuit` into another, ...
9,959
35.483516
489
py
pytket
pytket-main/examples/python/mapping_example.py
# # Respecting Device Constraints - Mapping physical circuits in TKET # In this tutorial we will show how the problem of mapping from logical quantum circuits to physically permitted circuits is solved automatically in TKET. The basic examples require only the installation of pytket, ```pip install pytket```. # Ther...
24,081
46.687129
793
py
pytket
pytket-main/examples/python/pytket-qujax_heisenberg_vqe.py
from pytket import Circuit from pytket.circuit.display import render_circuit_jupyter from jax import numpy as jnp, random, vmap, grad, value_and_grad, jit import matplotlib.pyplot as plt import qujax from pytket.extensions.qujax import tk_to_qujax # # Let's start with a tket circuit # We place barriers to stop tket a...
7,440
42.261628
398
py
pytket
pytket-main/examples/python/ucc_vqe.py
# # VQE for Unitary Coupled Cluster using tket # In this tutorial, we will focus on: # - building parameterised ansätze for variational algorithms; # - compilation tools for UCC-style ansätze. # This example assumes the reader is familiar with the Variational Quantum Eigensolver and its application to electronic stru...
23,593
44.724806
792
py
pytket
pytket-main/manual/conf.py
# -*- coding: utf-8 -*- # Configuration file for the Sphinx documentation builder. # See https://www.sphinx-doc.org/en/master/usage/configuration.html copyright = "2020-2023 Quantinuum" author = "Quantinuum" extensions = [ "sphinx.ext.autodoc", "sphinx.ext.autosummary", "sphinx.ext.intersphinx", "sph...
1,109
22.617021
78
py
Resemblyzer
Resemblyzer-master/demo03_projection.py
from resemblyzer import preprocess_wav, VoiceEncoder from demo_utils import * from itertools import groupby from pathlib import Path from tqdm import tqdm import numpy as np # DEMO 03: we'll show one way to visualize these utterance embeddings. Since they are # 256-dimensional, it is much simpler for us to get an ov...
1,263
38.5
99
py
Resemblyzer
Resemblyzer-master/demo02_diarization.py
from resemblyzer import preprocess_wav, VoiceEncoder from demo_utils import * from pathlib import Path # DEMO 02: we'll show how this similarity measure can be used to perform speaker diarization # (telling who is speaking when in a recording). ## Get reference audios # Load the interview audio from disk # Source f...
2,019
44.909091
92
py
Resemblyzer
Resemblyzer-master/setup.py
from setuptools import setup, find_packages with open("README.md", "r") as f: long_description = f.read() with open("requirements_package.txt", "r") as f: requirements = f.read().splitlines() setup( name="Resemblyzer", version="0.1.3", packages=find_packages(), package_data={ "resembl...
878
28.3
64
py
Resemblyzer
Resemblyzer-master/demo_utils.py
from mpl_toolkits.axes_grid1 import make_axes_locatable from matplotlib.animation import FuncAnimation from resemblyzer import sampling_rate from matplotlib import cm from time import sleep, perf_counter as timer from umap import UMAP from sys import stderr import matplotlib.pyplot as plt import numpy as np _default_c...
6,793
32.633663
96
py
Resemblyzer
Resemblyzer-master/demo05_fake_speech_detection.py
from resemblyzer import preprocess_wav, VoiceEncoder from demo_utils import * from pathlib import Path from tqdm import tqdm import numpy as np # DEMO 05: In this demo we'll show how we can achieve a modest form of fake speech detection with # Resemblyzer. This method assumes you have some reference audio for the ta...
2,863
42.393939
100
py
Resemblyzer
Resemblyzer-master/demo04_clustering.py
from sklearn.linear_model import LogisticRegression from resemblyzer import preprocess_wav, VoiceEncoder from demo_utils import * from pathlib import Path from tqdm import tqdm import numpy as np # DEMO 04: building from the previous demonstration, we'll show how natural properties of the # voice can emerge through...
2,928
46.241935
97
py
Resemblyzer
Resemblyzer-master/demo01_similarity.py
from resemblyzer import preprocess_wav, VoiceEncoder from demo_utils import * from itertools import groupby from pathlib import Path from tqdm import tqdm import matplotlib.pyplot as plt import numpy as np # The demos are ordered so as to make the explanations in the comments consistent. If you only # care about run...
4,336
51.253012
103
py
Resemblyzer
Resemblyzer-master/resemblyzer/audio.py
from scipy.ndimage.morphology import binary_dilation from resemblyzer.hparams import * from pathlib import Path from typing import Optional, Union import numpy as np import webrtcvad import librosa import struct int16_max = (2 ** 15) - 1 def preprocess_wav(fpath_or_wav: Union[str, Path, np.ndarray], source_sr: Optio...
4,352
38.93578
97
py
Resemblyzer
Resemblyzer-master/resemblyzer/hparams.py
## Mel-filterbank mel_window_length = 25 # In milliseconds mel_window_step = 10 # In milliseconds mel_n_channels = 40 ## Audio sampling_rate = 16000 # Number of spectrogram frames in a partial utterance partials_n_frames = 160 # 1600 ms ## Voice Activation Detection # Window size of the VAD. Must be either...
913
25.882353
88
py
Resemblyzer
Resemblyzer-master/resemblyzer/voice_encoder.py
from resemblyzer.hparams import * from resemblyzer import audio from pathlib import Path from typing import Union, List from torch import nn from time import perf_counter as timer import numpy as np import torch class VoiceEncoder(nn.Module): def __init__(self, device: Union[str, torch.device]=None, verbose=True,...
9,191
50.640449
114
py
Resemblyzer
Resemblyzer-master/resemblyzer/__init__.py
name = "resemblyzer" from resemblyzer.audio import preprocess_wav, wav_to_mel_spectrogram, trim_long_silences, \ normalize_volume from resemblyzer.hparams import sampling_rate from resemblyzer.voice_encoder import VoiceEncoder
232
32.285714
91
py
rebias
rebias-master/main_biased_mnist.py
"""ReBias Copyright (c) 2020-present NAVER Corp. MIT license Entry point of Biased-MNIST experiments. This script provides full implementations including - Various methods (ReBias, Vanilla, Biased, LearnedMixIn, RUBi) - Target network: Stacked convolutional networks (kernel_size=7) - Biased network: Stacked c...
5,724
40.18705
95
py
rebias
rebias-master/logger.py
"""ReBias Copyright (c) 2020-present NAVER Corp. MIT license """ import logging class LoggerBase(object): def __init__(self, **kwargs): self.level = kwargs.get('level', logging.DEBUG) self.logger = self.set_logger(**kwargs) def set_logger(self, **kwargs): return def log(self, msg...
2,318
27.62963
80
py
rebias
rebias-master/evaluator.py
"""ReBias Copyright (c) 2020-present NAVER Corp. MIT license """ import torch import numpy as np def n_correct(pred, labels): _, predicted = torch.max(pred.data, 1) n_correct = (predicted == labels).sum().item() return n_correct class EvaluatorBase(object): def __init__(self, device='cuda'): ...
11,149
37.184932
122
py
rebias
rebias-master/make_clusters.py
"""ReBias Copyright (c) 2020-present NAVER Corp. MIT license """ import argparse import os import time import torch import torch.nn as nn import torchvision from torchvision import transforms from torchvision.utils import save_image import numpy as np from PIL import Image from sklearn.cluster import MiniBatchKMeans...
5,502
34.503226
105
py
rebias
rebias-master/main_imagenet.py
"""ReBias Copyright (c) 2020-present NAVER Corp. MIT license Entry point of 9-Class ImageNet experiments. This script provides full implementations including - Various methods (ReBias, Vanilla, Biased, LearnedMixIn, RUBi) - Target network: ResNet-18 - Biased network: BagNet-18 - We do not provide Stylised...
5,975
36.822785
89
py
rebias
rebias-master/trainer.py
"""ReBias Copyright (c) 2020-present NAVER Corp. MIT license Unified implementation of the de-biasing minimax optimisation by various methods including, - ReBias (ours, outer_criterion='RbfHSIC', inner criterion='MinusRbfHSIC') - Vanilla and Biased baselines (f_lambda_outer=0, g_lambda_inner=0) - Learned Mixin (outer_...
20,817
42.280665
144
py
rebias
rebias-master/main_action.py
"""ReBias Copyright (c) 2020-present NAVER Corp. MIT license Entry point of Kinetics experiments. NOTE: We will not handle the issues from action recognition experiments. This script provides full implementations including - Various methods (ReBias, Vanilla, Biased, LearnedMixIn, RUBi) - Target network: ResNet3D ...
7,427
38.935484
92
py
rebias
rebias-master/optims/__init__.py
"""ReBias Copyright (c) 2020-present NAVER Corp. MIT license Opitmizers for the training. """ from torch.optim import Adam from torch.optim.lr_scheduler import StepLR, CosineAnnealingLR from adamp import AdamP __optim__ = ['Adam', 'AdamP'] __scheduler__ = ['StepLR', 'CosineAnnealingLR'] __all__ = ['Adam', 'AdamP',...
977
24.736842
88
py
rebias
rebias-master/criterions/comparison_methods.py
"""ReBias Copyright (c) 2020-present NAVER Corp. MIT license De-biasing comparison methods. Cadene, Remi, et al. "RUBi: Reducing Unimodal Biases for Visual Question Answering.", Clark, Christopher, Mark Yatskar, and Luke Zettlemoyer. "Don't Take the Easy Way Out: Ensemble Based Methods for Avoiding Known Dataset Biase...
3,496
34.683673
157
py
rebias
rebias-master/criterions/sigma_utils.py
"""ReBias Copyright (c) 2020-present NAVER Corp. MIT license """ import numpy as np import torch def _l2_dist(X): X = X.view(len(X), -1) XX = X @ X.t() X_sqnorms = torch.diag(XX) X_L2 = -2 * XX + X_sqnorms.unsqueeze(1) + X_sqnorms.unsqueeze(0) return X_L2.clone().detach().cpu().numpy().reshape(-1)...
1,810
26.029851
99
py
rebias
rebias-master/criterions/hsic.py
"""ReBias Copyright (c) 2020-present NAVER Corp. MIT license Python Implementation of the finite sample estimator of Hilbert-Schmidt Independence Criterion (HSIC) We provide both biased estimator and unbiased estimators (unbiased estimator is used in the paper) """ import torch import torch.nn as nn def to_numpy(x):...
4,434
33.648438
172
py
rebias
rebias-master/criterions/dist.py
"""ReBias Copyright (c) 2020-present NAVER Corp. MIT license Distance-based objective functions. Re-implemented for the compatibility with other losses """ import torch.nn as nn import torch.nn.functional as F class MSELoss(nn.Module): """ A simple mean squared error (MSE) implementation. """ def __init_...
858
25.84375
66
py
rebias
rebias-master/criterions/__init__.py
"""Criterions for de-biased representations. This module contains three different types of criterions. - HSIC: independence-based criterion used by ReBias (ours). - Distance: L2 and L1 losses. - Comparison methods: RUBi and LearnedMixin for comparisons. """ from criterions.hsic import RbfHSIC, MinusRbfHSIC from criter...
772
32.608696
80
py
rebias
rebias-master/models/rebias_models.py
"""ReBias Copyright (c) 2020-present NAVER Corp. MIT license ReBias model wrapper. """ import torch.nn as nn class ReBiasModels(object): """A container for the target network and the intentionally biased network. """ def __init__(self, f_net, g_nets): self.f_net = f_net self.g_nets = g_ne...
1,620
23.560606
79
py
rebias
rebias-master/models/imagenet_models.py
"""ResNet and BagNet implementations. original codes - https://github.com/pytorch/vision/blob/master/torchvision/models/resnet.py - https://github.com/wielandbrendel/bag-of-local-features-models/blob/master/bagnets/pytorchnet.py """ import torch import torch.nn as nn import math from torch.utils.model_zoo import load_u...
15,233
38.466321
159
py
rebias
rebias-master/models/mnist_models.py
"""ReBias Copyright (c) 2020-present NAVER Corp. MIT license Implementation for simple statcked convolutional networks. """ import torch import torch.nn as nn class SimpleConvNet(nn.Module): def __init__(self, num_classes=None, kernel_size=7, feature_pos='post'): super(SimpleConvNet, self).__init__() ...
2,049
32.606557
86
py
rebias
rebias-master/models/__init__.py
"""ReBias Copyright (c) 2020-present NAVER Corp. MIT license Target architectures and intentionally biased architectures for three benchmarks - MNIST: deep stacked convolutional networks with different kernel size, i.e., 7 (target) and 1 (biased). - ImageNet: ResNet-18 (target) and BagNet-18 (biased). - Kinetics: spat...
891
34.68
105
py
rebias
rebias-master/models/action_models/ResNet3D.py
import torch.nn as nn from .weight_init_helper import init_weights from .stem_helper import VideoModelStem from .resnet_helper import ResStage from .head_helper import ResNetBasicHead # Number of blocks for different stages given the model depth. _MODEL_STAGE_DEPTH = {18.1: (2, 2, 2, 2), 18: (2, ...
8,939
33.921875
74
py
rebias
rebias-master/models/action_models/nonlocal_helper.py
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. """Non-local helper""" import torch import torch.nn as nn class Nonlocal(nn.Module): """ Builds Non-local Neural Networks as a generic family of building blocks for capturing long-range dependencies. Non-local...
6,320
37.542683
80
py
rebias
rebias-master/models/action_models/head_helper.py
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. """ResNe(X)t Head helper.""" import torch import torch.nn as nn class ResNetBasicHead(nn.Module): """ ResNe(X)t 3D head. This layer performs a fully-connected projection during training, when the input siz...
5,073
36.308824
94
py
rebias
rebias-master/models/action_models/stem_helper.py
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. """ResNe(X)t 3D stem helper.""" import torch.nn as nn class VideoModelStem(nn.Module): """ Video 3D stem module. Provides stem operations of Conv, BN, ReLU, MaxPool on input data tensor for one or multiple pat...
5,867
33.116279
82
py
rebias
rebias-master/models/action_models/__init__.py
"""Kinetics model implementations. Original codes: https://github.com/facebookresearch/SlowFast """
100
24.25
60
py
rebias
rebias-master/models/action_models/weight_init_helper.py
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. """Utility function for weight initialization""" import torch.nn as nn from fvcore.nn.weight_init import c2_msra_fill def init_weights(model, fc_init_std=0.01, zero_init_final_bn=True): """ Performs ResNet style w...
1,444
33.404762
76
py
rebias
rebias-master/models/action_models/resnet_helper.py
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. """Video models.""" import torch.nn as nn from .nonlocal_helper import Nonlocal def get_trans_func(name): """ Retrieves the transformation module by name. """ trans_funcs = { "bottleneck_transform...
17,499
33.448819
83
py
rebias
rebias-master/datasets/colour_mnist.py
"""ReBias Copyright (c) 2020-present NAVER Corp. MIT license Python implementation of Biased-MNIST. """ import os import numpy as np from PIL import Image import torch from torch.utils import data from torchvision import transforms from torchvision.datasets import MNIST class BiasedMNIST(MNIST): """A base clas...
7,875
40.235602
124
py
rebias
rebias-master/datasets/__init__.py
"""ReBias Copyright (c) 2020-present NAVER Corp. MIT license Datasets used for the ``unbaised'' benchmarks - Biased-MNIST: synthetic bias with background colours. - 9-Class ImageNet: realistic bias where the unbiased performances are computed by the proxy texture labels (by texture clustering). - Kinetics-10: a su...
1,110
41.730769
149
py
rebias
rebias-master/datasets/kinetics.py
"""ReBias Copyright (c) 2020-present NAVER Corp. MIT license Dataset for the action recognition benchmarks. We use the official implemenation of SlowFast by Facebook research. https://github.com/facebookresearch/SlowFast """ import torch from datasets.kinetics_tools.loader import construct_loader def get_kinetics_d...
831
32.28
67
py
rebias
rebias-master/datasets/imagenet.py
"""ReBias Copyright (c) 2020-present NAVER Corp. MIT license 9-Class ImageNet wrapper. Many codes are borrowed from the official torchvision dataset. https://github.com/pytorch/vision/blob/master/torchvision/datasets/imagenet.py The following nine classes are selected to build the subset: dog, cat, frog, turtle, ...
6,565
38.317365
97
py
rebias
rebias-master/datasets/kinetics_tools/video_container.py
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. import av def get_video_container(path_to_vid): """ Given the path to the video, return the pyav video container. Args: path_to_vid (str): patth to the video. Returns: container (container):...
409
23.117647
71
py
rebias
rebias-master/datasets/kinetics_tools/transform.py
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. import math import numpy as np import torch def random_short_side_scale_jitter(images, min_size, max_size): """ Perform a spatial short scale jittering on the given images. Args: images (tensor): images...
3,922
31.155738
79
py
rebias
rebias-master/datasets/kinetics_tools/decoder.py
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. import math import numpy as np import random import torch def temporal_sampling(frames, start_idx, end_idx, num_samples): """ Given the start and end frame index, sample num_samples frames between the start and...
8,893
36.527426
80
py
rebias
rebias-master/datasets/kinetics_tools/__init__.py
"""Kinetics dataset implementations. Original codes: https://github.com/facebookresearch/SlowFast """
102
24.75
60
py
rebias
rebias-master/datasets/kinetics_tools/kinetics.py
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. import os import json import random import torch import torch.utils.data import datasets.kinetics_tools.decoder as decoder import datasets.kinetics_tools.video_container as container import datasets.kinetics_tools.transform...
17,839
40.488372
118
py
rebias
rebias-master/datasets/kinetics_tools/loader.py
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. """Data loader.""" import torch from torch.utils.data.distributed import DistributedSampler from torch.utils.data.sampler import RandomSampler from datasets.kinetics_tools.kinetics import Kinetics # Supported datasets. _D...
2,473
29.925
71
py
rebias
rebias-master/datasets/kinetics_tools/meters.py
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. """Meters.""" import datetime import numpy as np from collections import deque import torch import time import slowfast.utils.logging as logging import slowfast.utils.metrics as metrics from fvcore.common.timer import Tim...
13,430
31.442029
80
py
rebias
rebias-master/datasets/mimetics/download.py
import argparse import glob import json import os import shutil import subprocess import uuid from collections import OrderedDict from joblib import delayed from joblib import Parallel import pandas as pd def create_video_folders(dataset, output_dir, tmp_dir): """Creates a directory for each label name in the da...
8,387
36.28
79
py
TraBS
TraBS-main/setup.py
from setuptools import setup, find_packages with open('README.md', encoding='utf-8') as f: long_description = f.read() with open('requirements.txt', encoding='utf-8') as f: install_requires = f.read() setup( name='TraBS', author="Gustav Müller-Franzes", version=1, description="Neural Networ...
550
26.55
65
py
TraBS
TraBS-main/scripts/main_pretrain.py
from pathlib import Path from datetime import datetime import torch from pytorch_lightning.trainer import Trainer from pytorch_lightning.callbacks import EarlyStopping, ModelCheckpoint import numpy as np import torchio as tio from breaststudies.data import BreastDataModule, BreastDataModuleLR, BreastDataModule2D...
5,913
39.506849
179
py
TraBS
TraBS-main/scripts/main_compute_segmentation_quality.py
import logging from pathlib import Path import numpy as np import pandas as pd import monai.metrics as mm import torchio as tio from breaststudies.utils import one_hot from breaststudies.metrics import compute_surface_distances, compute_average_surface_distance from breaststudies.data import BreastDatasetCreator,...
4,308
36.469565
168
py
TraBS
TraBS-main/scripts/main_train.py
from pathlib import Path from datetime import datetime import torch from pytorch_lightning.trainer import Trainer from pytorch_lightning.callbacks import EarlyStopping, ModelCheckpoint import numpy as np import torchio as tio from breaststudies.data import BreastDataModule, BreastDataModuleLR, BreastDataModule2D,...
6,986
42.12963
191
py
TraBS
TraBS-main/scripts/main_predict.py
from pathlib import Path from datetime import datetime from shutil import copyfile import logging import numpy as np import torch import torch.nn.functional as F import SimpleITK as sitk import torchio as tio from breaststudies.data import BreastDatasetCreator from breaststudies.models import UNet, nnUNet, SwinUN...
6,468
41.559211
146
py
TraBS
TraBS-main/scripts/main_predict_kfold.py
from pathlib import Path from shutil import copyfile import logging import sys import numpy as np import torch import torchio as tio import SimpleITK as sitk from monai.metrics import compute_meandice from breaststudies.augmentation.augmentations import Resample2, ZNormalization, ToOrientation, RandomDisableChan...
8,639
44.235602
213
py
TraBS
TraBS-main/breaststudies/postprocessing/__init__.py
from .remove_fragments import close_holes, keep_connected, keep_inside
70
70
70
py
TraBS
TraBS-main/breaststudies/postprocessing/remove_fragments.py
import scipy.ndimage as ndimage import skimage.measure as measure import numpy as np def _keep_connected_binary(binary_mask, voxel_vol, min_volume=None, keep_only_largest=1): if keep_only_largest==0: return np.zeros(binary_mask.shape, dtype=binary_mask.dtype) mask_ind, num_features = measure.label(...
2,684
40.953125
161
py
TraBS
TraBS-main/breaststudies/models/swin_unetr.py
from breaststudies.models import BasicModel import breaststudies.models.monai_mods as nets class SwinUNETR(BasicModel): def __init__(self, in_ch, out_ch, roi_size, spatial_dims = 3, patch_sizes = ( (1,2,2), (1,2,2), 2, 2), ...
1,286
25.265306
69
py
TraBS
TraBS-main/breaststudies/models/basic_unet.py
from breaststudies.models import BasicModel import monai.networks.nets as nets class UNet(BasicModel): def __init__( self, in_ch, out_ch, roi_size, spatial_dims=3, **kwargs ): super().__init__(in_ch, out_ch, roi_size, **kwargs) self.model =...
550
19.407407
103
py
TraBS
TraBS-main/breaststudies/models/basic_model.py
from pathlib import Path import json import torch import torch.nn.functional as F import pytorch_lightning as pl from torchvision.utils import save_image from pytorch_lightning.utilities.cloud_io import load as pl_load from pytorch_lightning.utilities.migration import pl_legacy_patch from pytorch_msssim import ssim f...
9,994
43.820628
169
py
TraBS
TraBS-main/breaststudies/models/nn_unet.py
from breaststudies.models import BasicModel import monai.networks.nets as nets class nnUNet(BasicModel): def __init__( self, in_ch, out_ch, roi_size, spatial_dims=3, kernel_size=[[1,3,3], [1,3,3], 3, 3,3], strides= [ 1, [1,2,2], [1,2,2],2,2]...
1,961
34.672727
177
py
TraBS
TraBS-main/breaststudies/models/__init__.py
from .basic_model import BasicModel from .basic_unet import UNet from .nn_unet import nnUNet from .swin_unetr import SwinUNETR
126
30.75
35
py
TraBS
TraBS-main/breaststudies/models/monai_mods/swin_unetr.py
# Copyright (c) MONAI Consortium # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, so...
38,039
39.947255
473
py
TraBS
TraBS-main/breaststudies/models/monai_mods/__init__.py
from .swin_unetr import SwinUNETR, SwinTransformer
50
50
50
py
TraBS
TraBS-main/breaststudies/models/monai_mods/blocks.py
from typing import Sequence, Type, Union import numpy as np import torch import torch.nn as nn import torch.nn.functional as F from torch.nn import LayerNorm from monai.networks.layers import Conv, trunc_normal_ from monai.utils import ensure_tuple_rep, optional_import from monai.utils.module import look_up_option R...
3,877
36.650485
111
py
TraBS
TraBS-main/breaststudies/metrics/deepmind_lookuptable.py
##################### # https://github.com/deepmind/surface-distance ####################### # Copyright 2018 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License a...
22,852
55.42716
101
py
TraBS
TraBS-main/breaststudies/metrics/deepmind_distances.py
##################### # https://github.com/deepmind/surface-distance ####################### # Copyright 2018 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License a...
18,504
40.213808
111
py
TraBS
TraBS-main/breaststudies/metrics/__init__.py
from .deepmind_distances import compute_average_surface_distance, compute_surface_distances
91
91
91
py
TraBS
TraBS-main/breaststudies/augmentation/augmentations.py
from typing import Iterable, Tuple, Union, List, Optional, Sequence, Dict from numbers import Number from pathlib import Path import warnings from tqdm import tqdm import numpy as np import nibabel as nib import torch import torchio as tio from torchio import Subject, RandomAffine, IntensityTransform, CropOrPad, Re...
31,025
40.983762
167
py
TraBS
TraBS-main/breaststudies/augmentation/helper_functions.py
import numpy as np from skimage.transform import resize from skimage.transform import resize from scipy.ndimage.interpolation import map_coordinates from collections import OrderedDict RESAMPLING_SEPARATE_Z_ANISO_THRESHOLD = 3 def uniform(low, high, size=None): """ wrapper for np.random.uniform to allo...
14,633
39.65
155
py