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
episodic-curiosity
episodic-curiosity-master/episodic_curiosity/keras_checkpoint.py
# coding=utf-8 # Copyright 2019 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 ...
3,669
38.891304
79
py
OrcaNet
OrcaNet-master/orcanet/core.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Core scripts for the OrcaNet package. """ import os import toml import warnings import time from datetime import timedelta import tensorflow as tf import orcanet.backend as backend from orcanet.utilities.visualization import update_summary_plot from orcanet.in_out imp...
37,957
38.05144
116
py
OrcaNet
OrcaNet-master/orcanet/h5_generator.py
import h5py import time import numpy as np import tensorflow as tf import tensorflow.keras as ks class Hdf5BatchGenerator(ks.utils.Sequence): def __init__(self, files_dict, batchsize=64, key_x_values="x", key_y_values="y", sample_modifier=None, ...
19,171
35.798464
93
py
OrcaNet
OrcaNet-master/orcanet/logging.py
""" Scripts for writing the logfiles. """ import numpy as np import os import tensorflow.keras as ks from datetime import datetime from shutil import move import orcanet class TrainfileLogger: def __init__(self, log_file, column_names): """ For writing the training log file in a nice format. ...
20,985
34.690476
124
py
OrcaNet
OrcaNet-master/orcanet/in_out.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Utility code regarding user input. """ import os import shutil import h5py import numpy as np from inspect import signature # moved into IOHandler.get_batch for speed up; tensorflow import is slow! # from orcanet.h5_generator import Hdf5BatchGenerator def get_subfol...
28,848
32.236175
97
py
OrcaNet
OrcaNet-master/orcanet/model_builder.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Scripts for making specific models. """ import warnings import toml from datetime import datetime import tensorflow as tf import tensorflow.keras as ks import tensorflow.keras.layers as layers from orcanet.builder_util.builders import BlockBuilder class ModelBuilder...
14,663
34.678832
107
py
OrcaNet
OrcaNet-master/orcanet/backend.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Code for training and validating NN's, as well as evaluating them. """ import time import h5py import numpy as np import os import orcanet from orcanet.logging import BatchLogger import orcanet.utilities.nn_utilities as nn_utilities from orcanet.in_out import h5_get_nu...
11,537
34.721362
89
py
OrcaNet
OrcaNet-master/orcanet/builder_util/layer_blocks.py
import tensorflow as tf import tensorflow.keras.backend as K import tensorflow.keras as ks import tensorflow.keras.layers as layers import medgeconv from orcanet.misc import get_register # for loading via toml and orcanet custom objects blocks, register = get_register() # edge conv blocks register(medgeconv.DisjointEd...
29,127
34.306667
106
py
OrcaNet
OrcaNet-master/orcanet/builder_util/builders.py
import inspect import warnings import tensorflow.keras as ks import tensorflow.keras.layers as layers import orcanet.builder_util.layer_blocks as layer_blocks class BlockBuilder: """ Builds single-input block-wise sequential neural network. Parameters ---------- defaults : dict or None D...
8,125
31.374502
84
py
OrcaNet
OrcaNet-master/orcanet/utilities/nn_utilities.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """Utility functions used for training a NN.""" import warnings import numpy as np import h5py import os import time import tensorflow.keras as ks from functools import reduce class RaiseOnNaN(ks.callbacks.Callback): """ Callback that terminates training when a N...
9,113
32.630996
80
py
OrcaNet
OrcaNet-master/orcanet/tests/test_logging.py
from unittest import TestCase from unittest.mock import MagicMock import os from tensorflow.keras.models import Model import tensorflow.keras.layers as layers import numpy as np import shutil from orcanet.logging import SummaryLogger, merge_arrays, BatchLogger, gen_line_str from orcanet.core import Organizer class T...
11,911
36.815873
133
py
OrcaNet
OrcaNet-master/orcanet/tests/test_core.py
import tempfile from unittest import TestCase from unittest.mock import MagicMock, patch import os import shutil import tensorflow as tf from tensorflow.keras.models import Model import tensorflow.keras.layers as layers from orcanet.core import Organizer, Configuration, _extract_filepaths class TestOrganizer(tf.test...
13,945
33.952381
112
py
OrcaNet
OrcaNet-master/orcanet/tests/test_nn_utilities.py
#!/usr/bin/env python # -*- coding: utf-8 -*- import numpy as np import os import shutil import h5py from unittest import TestCase from tensorflow.keras.models import Model import tensorflow.keras.layers as layers from orcanet.core import Organizer from orcanet.utilities.nn_utilities import load_zero_center_data cl...
5,791
33.47619
85
py
OrcaNet
OrcaNet-master/orcanet/tests/test_in_out.py
from unittest import TestCase from unittest.mock import MagicMock import os import h5py import numpy as np import shutil from pathlib import Path from tensorflow.keras.models import Model import tensorflow.keras.layers as layers from orcanet.core import Configuration from orcanet.in_out import IOHandler, split_name_of...
23,989
32.044077
118
py
OrcaNet
OrcaNet-master/orcanet/tests/test_model_builder.py
#!/usr/bin/env python # -*- coding: utf-8 -*- import os from unittest import TestCase from unittest.mock import MagicMock, patch import tensorflow.keras as ks import tensorflow.keras.layers as layers from orcanet.core import Organizer from orcanet.model_builder import ModelBuilder from orcanet_contrib.custom_objects ...
4,117
34.5
91
py
OrcaNet
OrcaNet-master/orcanet/tests/test_backend.py
import tempfile from unittest import TestCase from unittest.mock import MagicMock import os import warnings import h5py import numpy as np import tensorflow as tf import tensorflow.keras as ks import tensorflow.keras.layers as layers from orcanet.core import Organizer from orcanet.backend import train_model, validate_...
9,186
28.445513
105
py
OrcaNet
OrcaNet-master/orcanet/tests/test_layer_blocks.py
from unittest import TestCase import tensorflow as tf import orcanet.builder_util.layer_blocks as layer_blocks class TestInceptionBlockV2(TestCase): def setUp(self): self.inp_2d = tf.keras.layers.Input(shape=(10, 10, 1)) self.inp_3d = tf.keras.layers.Input(shape=(10, 10, 10, 1)) def test_sha...
6,942
30.559091
94
py
OrcaNet
OrcaNet-master/orcanet/tests/test_builders.py
import tensorflow as tf from tensorflow.keras.models import Model import tensorflow.keras.layers as layers from orcanet.builder_util.builders import BlockBuilder class TestSequentialBuilder(tf.test.TestCase): def test_input_names_and_shapes_full_model(self): defaults = {"type": "conv_block", "conv_dim":...
4,727
35.9375
111
py
OrcaNet
OrcaNet-master/orcanet/tests/test_model_setup.py
# removed, as testing whether changing dropout works requires # get layer output, which doesn't work properly in tf 2.1 import unittest import numpy as np import tensorflow.keras as ks import tensorflow.keras.layers as layers from orcanet.model_builder import _change_dropout_rate @unittest.skip("skipped, as testing...
3,731
43.428571
81
py
OrcaNet
OrcaNet-master/orcanet/tests/test_h5_generator.py
import tempfile from unittest import TestCase from unittest.mock import MagicMock import os import numpy as np from orcanet.core import Organizer from orcanet.h5_generator import get_h5_generator from orcanet.tests.test_backend import save_dummy_h5py, assert_dict_arrays_equal, assert_equal_struc_array class TestBatc...
6,914
34.64433
106
py
OrcaNet
OrcaNet-master/orcanet/tests/test_losses.py
import numpy as np import tensorflow as tf import orcanet.lib.losses as on_losses class TestLklNormal(tf.test.TestCase): def setUp(self): self.loss_func = on_losses.lkl_normal self.y_pred = tf.constant([ [[0], [1]], [[1], [1]], [[2], [2]], ], dtype="floa...
1,576
29.326923
79
py
OrcaNet
OrcaNet-master/orcanet/lib/label_modifiers.py
import warnings import numpy as np import orcanet.misc as misc # for loading via toml lmods, register = misc.get_register() class ColumnLabels: """ Label of each model output is column with the same name in the h5 file. This is the default label modifier. Example ------- Model has output "en...
9,650
30.642623
162
py
OrcaNet
OrcaNet-master/examples/full_example/full_example.py
import numpy as np import h5py from tensorflow.keras.layers import Input, Dense from tensorflow.keras.models import Model import os from orcanet.core import Organizer def make_dummy_data(path): """ Save a train and a val h5 file with random numbers as samples, and the sum as labels. """ def get_...
1,557
21.257143
66
py
OrcaNet
OrcaNet-master/orcanet_contrib/custom_objects.py
import tensorflow.keras.backend as K import tensorflow as tf import math def get_custom_objects(): """ Functions that returns a dict with all relevant loss functions in this file. """ custom_objects = { 'loss_direction': loss_direction, 'loss_uncertainty_mse': loss_uncertainty_mse, ...
11,457
43.239382
153
py
OrcaNet
OrcaNet-master/orcanet_contrib/parser_orcatrain.py
""" Use orga.train with a parser. Usage: parser_orcatrain.py [options] FOLDER LIST CONFIG MODEL parser_orcatrain.py (-h | --help) Arguments: FOLDER Path to the folder where everything gets saved to, e.g. the summary.txt, the plots, the trained models, etc. LIST A .toml file which conta...
4,173
34.372881
90
py
OrcaNet
OrcaNet-master/docs/conf.py
# -*- coding: utf-8 -*- # # Configuration file for the Sphinx documentation builder. # # This file does only contain a selection of the most common options. For a # full list see the documentation: # http://www.sphinx-doc.org/en/master/config # -- Path setup ------------------------------------------------------------...
6,834
28.847162
79
py
OrcaNet
OrcaNet-master/scraps/conv4d.py
from __future__ import division import tensorflow as tf import numpy as np def conv4d( input_tensor, filters, kernel_size=(3, 3, 3, 3), strides=(1, 1, 1, 1), padding='valid', data_format='channels_first', dilation_rate=(1, 1, 1, 1), activation=None, ...
5,958
30.86631
76
py
OrcaNet
OrcaNet-master/scraps/test_model.py
from tensorflow.keras.models import Model, clone_model import tensorflow.keras.layers as layers import numpy as np from tensorflow.keras import backend as K def build_double_inp(compile=False): inp_1 = layers.Input((1,), name="inp_0") inp_2 = layers.Input((1,), name="inp_1") x = layers.Concatenate()([inp...
2,716
27.6
76
py
OrcaNet
OrcaNet-master/scraps/multi_gpu/multi_gpu_mixin_models.py
""" Multi-gpu code for Keras/TF. From https://github.com/avolkov1/keras_experiments """ from keras.legacy import interfaces from keras import callbacks as cbks __all__ = ('ModelDataflowMixin',) class ModelDataflowMixin(object): @interfaces.legacy_generator_methods_support def fit_dataflow(self, dflow, ...
11,545
43.751938
79
py
OrcaNet
OrcaNet-master/scraps/multi_gpu/multi_gpu_patch_tf_backend.py
""" Multi-gpu code for Keras/TF. From https://github.com/avolkov1/keras_experiments """ import sys import numpy as np import tensorflow as tf from keras.backend import tensorflow_backend as tfb from keras.backend.tensorflow_backend import (get_session, is_sparse) import atexit atexit.register(tfb.clear_session) # F...
3,824
38.43299
79
py
OrcaNet
OrcaNet-master/scraps/multi_gpu/multi_gpu.py
# -*- coding: utf-8 -*- """ Multi-gpu code for Keras/TF. From https://github.com/avolkov1/keras_experiments """ # MODIFIED. Inspiration taken from the ref link below. # ref: https://raw.githubusercontent.com/kuza55/keras-extras/master/utils/multi_gpu.py @IgnorePep8 # The inspirational one carried license: # Apache ...
39,536
42.209836
134
py
OrcaNet
OrcaNet-master/scraps/old_model_scripts/wide_resnet.py
# -*- coding: utf-8 -*- """Wide Residual Network models for Keras. Loosely based on https://github.com/titu1994/Wide-Residual-Networks/blob/master/wide_residual_network.py # Reference - [Wide Residual Networks](https://arxiv.org/abs/1605.07146) """ from keras.models import Model from keras.layers import Input, Add, Ac...
12,278
44.64684
169
py
OrcaNet
OrcaNet-master/scraps/old_model_scripts/short_cnn_models.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """Functions for creating VGG-like models (including VGG-LSTM)""" import keras as ks from keras.models import Model from keras.layers import Input, Dense, Dropout, Activation, Flatten, Convolution3D, BatchNormalization, MaxPooling3D,\ Convolution2D...
35,658
44.252538
212
py
ilm
ilm-master/acl20_repro.py
PREMASKED_DATA = { 'train': { 'sto_mixture': 'https://drive.google.com/open?id=1LxlyPqz3OvAZsYRRC8yRdSoaCKGB0Ucg', 'abs_mixture': 'https://drive.google.com/open?id=1rw45GKP4iRJLzXnRtX-rnk_NeGXOqWkU', 'lyr_mixture': 'https://drive.google.com/open?id=1jGCjboxlFUF0jqvB0_-L0eeylhKWfZJV', }, 'valid': { ...
6,718
54.528926
360
py
ilm
ilm-master/acl20_repro_eval.py
from acl20_repro import PREMASKED_DATA, PRETRAINED_MODELS, PRETRAINED_MODEL_CONFIG_JSON, PAPER_TASK_TO_INTERNAL # NOTE: https://chrisdonahue.com/gdrive-wget _CMD_TEMPL = """ mkdir -p {eval_tmp_dir}/data mkdir -p {eval_tmp_dir}/models/{model_tag} # Download pre-masked data wget -nc --load-cookies /tmp/cookies.txt "htt...
2,610
38.560606
397
py
ilm
ilm-master/train_ilm.py
from enum import Enum from collections import defaultdict import multiprocessing import os import pickle import random import time import warnings import numpy as np import torch import torch.nn.functional as F from torch.utils.data import (DataLoader, RandomSampler, SequentialSampler, TensorDataset) from tqdm import ...
26,721
35.159675
168
py
ilm
ilm-master/ilm/infer.py
import copy import torch import torch.nn.functional as F def sample_from_logits( logits, temp=1., topk=None, nucleus=1.): if temp == 0: return torch.argmax(logits, dim=-1).unsqueeze(-1) elif temp != 1: logits /= temp probs = F.softmax(logits, dim=-1) if topk is not None: top...
3,227
26.355932
110
py
An-Empirical-Study-of-DFO-Algorithms-for-Targeted-Black-Box-Attacks-in-DNNs
An-Empirical-Study-of-DFO-Algorithms-for-Targeted-Black-Box-Attacks-in-DNNs-master/Setups/Attacks.py
""" This Script allows to run attacks to nets trained on either ImageNet or Cifar10 with or without the adversary defence by MadryLab. """ import os os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' import sys sys.path.append("./") import tensorflow as tf import torchvision.models as models_ch import torch as ch import numpy...
22,096
50.269142
150
py
An-Empirical-Study-of-DFO-Algorithms-for-Targeted-Black-Box-Attacks-in-DNNs
An-Empirical-Study-of-DFO-Algorithms-for-Targeted-Black-Box-Attacks-in-DNNs-master/Setups/Data_and_Model/setup_mnist.py
## setup_mnist.py -- mnist data and model loading code ## ## Copyright (C) IBM Corp, 2017-2018 ## Copyright (C) 2016, Nicholas Carlini <nicholas@carlini.com>. ## ## This program is licenced under the BSD 2-Clause licence, ## contained in the LICENCE file in this directory. import tensorflow as tf import numpy as np im...
3,939
36.52381
123
py
An-Empirical-Study-of-DFO-Algorithms-for-Targeted-Black-Box-Attacks-in-DNNs
An-Empirical-Study-of-DFO-Algorithms-for-Targeted-Black-Box-Attacks-in-DNNs-master/Setups/Data_and_Model/setup_cifar.py
## setup_cifar.py -- cifar data and model loading code ## ## Copyright (C) IBM Corp, 2017-2018 ## Copyright (C) 2016, Nicholas Carlini <nicholas@carlini.com>. ## ## This program is licenced under the BSD 2-Clause licence, ## contained in the LICENCE file in this directory. import tensorflow as tf import numpy as np i...
4,260
30.330882
118
py
An-Empirical-Study-of-DFO-Algorithms-for-Targeted-Black-Box-Attacks-in-DNNs
An-Empirical-Study-of-DFO-Algorithms-for-Targeted-Black-Box-Attacks-in-DNNs-master/Setups/Data_and_Model/wrapper_model_loss_f.py
""" This scripts allows to wrap the different instances of models and loss functions for the different attacks """ import numpy as np import torch as ch # Patch for single output def patch_single_output(x, single_output): if single_output: return x,0 return x #Models class Model_Class_combi(): d...
8,836
34.207171
99
py
An-Empirical-Study-of-DFO-Algorithms-for-Targeted-Black-Box-Attacks-in-DNNs
An-Empirical-Study-of-DFO-Algorithms-for-Targeted-Black-Box-Attacks-in-DNNs-master/Setups/Data_and_Model/save_MNIST_CIFAR_data.py
## train_models.py -- train the neural network models for attacking ## ## Copyright (C) IBM Corp, 2017-2018 ## Copyright (C) 2016, Nicholas Carlini <nicholas@carlini.com>. ## ## This program is licenced under the BSD 2-Clause licence, ## contained in the LICENCE file in this directory. import numpy as np from keras.m...
1,343
31.780488
107
py
An-Empirical-Study-of-DFO-Algorithms-for-Targeted-Black-Box-Attacks-in-DNNs
An-Empirical-Study-of-DFO-Algorithms-for-Targeted-Black-Box-Attacks-in-DNNs-master/Attack_Code/Combinatorial/tools/imagenet_labels.py
"""This script is borrowed from https://github.com/labsix/limited-blackbox-attacks""" _lut = [ 'tench, Tinca tinca', 'goldfish, Carassius auratus', 'great white shark, white shark, man-eater, man-eating shark, Carcharodon carcharias', 'tiger shark, Galeocerdo cuvieri', 'hammerhead, hammerhead shark...
28,838
27.581764
128
py
An-Empirical-Study-of-DFO-Algorithms-for-Targeted-Black-Box-Attacks-in-DNNs
An-Empirical-Study-of-DFO-Algorithms-for-Targeted-Black-Box-Attacks-in-DNNs-master/Attack_Code/Square_Attack/data.py
import torch import numpy as np from torchvision import transforms from torchvision.datasets import ImageFolder from torch.utils.data import DataLoader, Dataset def load_mnist(n_ex): from tensorflow.keras.datasets import mnist as mnist_keras x_test, y_test = mnist_keras.load_data()[1] x_test = x_test.ast...
1,623
30.843137
88
py
An-Empirical-Study-of-DFO-Algorithms-for-Targeted-Black-Box-Attacks-in-DNNs
An-Empirical-Study-of-DFO-Algorithms-for-Targeted-Black-Box-Attacks-in-DNNs-master/Attack_Code/Square_Attack/models.py
import torch import tensorflow as tf import numpy as np import math from torchvision import models as torch_models from torch.nn import DataParallel from madry_mnist.model import Model as madry_model_mnist from madry_cifar10.model import Model as madry_model_cifar10 from logit_pairing.models import LeNet as lp_model_mn...
6,688
44.195946
116
py
MaxStyle
MaxStyle-main/src/test_basic_segmentation_solver.py
# Created by cc215 at 02/05/19 # Modified by cc215 at 11/12/19 # This code is for testing basic segmentation networks # Steps: # 1. get the segmentation network and the path of checkpoint # 2. fetch images tuples from the disk to test the segmentation # 3. get the prediction result # 4. update the metric # 5. sav...
14,577
47.431894
144
py
MaxStyle
MaxStyle-main/src/train_adv_supervised_segmentation_triplet.py
from __future__ import print_function import sys import os import argparse import shutil from os.path import join, exists import gc import random from matplotlib import style import numpy as np import torch import torchio as tio import pandas as pd from torch.utils.tensorboard import SummaryWriter from torch.utils.dat...
60,272
61.719043
246
py
MaxStyle
MaxStyle-main/src/advanced/rand_conv_aug.py
''' Robust and Generalizable Visual Representation Learning via Random Convolutions https://arxiv.org/pdf/2007.13003.pdf ''' import random import torch import numpy as np class RandConvAug(): def __init__(self, kernel_size_candidates=[1, 3, 5, 7], prob=0.5, mix=True): self.kernel_size_candidates = kerne...
1,732
34.367347
96
py
MaxStyle
MaxStyle-main/src/advanced/mixup.py
# Created by cc215 at 13/12/19 import numpy as np import torch import sys sys.path.append('../') from src.models.custom_loss import One_Hot, cross_entropy_2D class MixUP(): def __init__(self, alpha=0.4, preserve_order=False, use_gpu=False, opt=None): ''' MIXUP training reference: https://g...
5,053
38.484375
119
py
MaxStyle
MaxStyle-main/src/advanced/mixstyle.py
import torch import torch.nn as nn import random class MixStyle(nn.Module): """MixStyle. code is adapted from the orginal mixstyle paper. Reference: Zhou et al. Domain Generalization with MixStyle. ICLR 2021. """ def __init__(self, p=0.5, alpha=0.1, eps=1e-8, mix='random', lmda=None, zero_i...
4,147
35.385965
153
py
MaxStyle
MaxStyle-main/src/advanced/random_window_masking.py
import random import torch def random_inpainting(image, cnt=5): """[summary] masking images with random window blocks, where values are randomly draw. code is adapted from Model Genesis: https://github.com/MrGiovanni/ModelsGenesis/blob/master/pytorch/utils.py Args: image ([ torch tensor]): a b...
3,142
38.78481
137
py
MaxStyle
MaxStyle-main/src/advanced/maxstyle.py
import torch import torch.nn as nn import random class MaxStyle(nn.Module): """MaxStyle Official implementation of MaxStyle: [MICCAI 2022] MaxStyle: Adversarial Style Composition for Robust Medical Image Segmentation code is adapted based on the orginal mixstyle implementation: https://github.com/KaiyangZ...
11,614
46.995868
237
py
MaxStyle
MaxStyle-main/src/models/custom_loss.py
import torchvision import math import torch import torch.nn.functional as F import torch.nn as nn from torch.autograd import Variable import numpy as np import sys sys.path.append('../') from src.common_utils.morphology import Dilation2d def basic_loss_fn(pred, target, loss_type='cross_entropy', class_weights=None, u...
52,752
37.171491
139
py
MaxStyle
MaxStyle-main/src/models/init_weight.py
from torch.nn import init import torch import torch.nn as nn import torch.nn as nn def reset_bn(model): # reset to reestimate bn normalization stats for n, m in model.named_modules(): if n.find('BatchNorm') != -1: m.reset_running_stats() def init_bn(model): # reset to reestimate bn n...
2,877
31.704545
94
py
MaxStyle
MaxStyle-main/src/models/advanced_triplet_recon_segmentation_model.py
# this segmentation model is composed of 2 subnetworks at least, an encoder and an decoder import itertools import random import os from os.path import join from tkinter import E from numpy import True_ from numpy.core.fromnumeric import shape import torch.nn as nn import torch import torch.optim as optim import gc i...
57,362
50.585432
244
py
MaxStyle
MaxStyle-main/src/models/model_util.py
import torch import torch.nn as nn from torch.autograd import Variable import numpy as np import torch import torch.nn as nn from torch.autograd import Variable import torch.nn.functional as F from torch.optim import lr_scheduler import numpy as np import contextlib import math import sys sys.path.append('../') # from ...
29,948
37.445443
177
py
MaxStyle
MaxStyle-main/src/models/custom_layers.py
import math import torch.nn as nn from torch.nn.modules.batchnorm import _BatchNorm from torch.nn.parameter import Parameter from torch.nn import functional as F import torch from torch.nn.utils import spectral_norm class Fixable2DDropout(nn.Module): """ _summary_method = torch.nn.Dropout2d.__init__ based...
16,379
36.568807
163
py
MaxStyle
MaxStyle-main/src/models/base_segmentation_model.py
# Created by cc215 at 02/05/19 # segmentation model definition goes here import os from os.path import join import torch.nn as nn import torch import torch.optim as optim import gc import traceback import sys sys.path.append('../') from src.models.init_weight import init_weights from src.models.segmentation_models.fc...
14,320
42.135542
140
py
MaxStyle
MaxStyle-main/src/models/segmentation_models/fcn.py
import torch.nn as nn import torch.nn.functional as F import torch import sys sys.path.append('../../') from src.models.init_weight import init_weights from src.models.segmentation_models.unet_parts import conv2DBatchNormRelu class FCN(nn.Module): # Wenjia Bai's FCN pytorch Implementation, for more details, pleas...
8,305
37.813084
118
py
MaxStyle
MaxStyle-main/src/models/segmentation_models/resconvunet.py
# Created by cc215 at 07/06/19 # same unet but use convolutional kernel to do downsampling and upsampling; plus residual connection after downsampling and upsampling # Enter scenario name here # Enter steps here import math import torch.nn as nn from torch.autograd import Variable import numpy as np import sys sys.pa...
8,312
38.966346
168
py
MaxStyle
MaxStyle-main/src/models/segmentation_models/unetr.py
## the code is adapted from MONAI: https://github.com/Project-MONAI/MONAI/blob/dev/monai/networks/nets/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...
19,323
39.174636
156
py
MaxStyle
MaxStyle-main/src/models/segmentation_models/unet_parts.py
#!/usr/bin/python # sub-parts of the U-Net models import torch import torch.nn as nn import torch.nn.functional as F from torch.nn.utils import spectral_norm import sys sys.path.append('../../') from src.models.init_weight import init_weights from src.models.custom_layers import Fixable2DDropout class CodeFilter(nn.M...
26,161
35.539106
150
py
MaxStyle
MaxStyle-main/src/models/segmentation_models/unet.py
import math import sys import torch.nn as nn from torch.autograd import Variable import numpy as np import sys sys.path.append('../../') from src.models.model_util import _disable_tracking_bn_stats from src.models.segmentation_models.unet_parts import * class UnetEncoder(nn.Module): def __init__(self, input_ch...
22,575
40.047273
167
py
MaxStyle
MaxStyle-main/src/models/ebm/encoder_decoder.py
import math import torch import torch.nn as nn from torch.autograd import Variable import numpy as np from torch.nn.utils import spectral_norm import torch.nn.functional as F import sys sys.path.append('../../') from src.models.custom_layers import DomainSpecificBatchNorm2d from src.models.custom_layers import Fixable...
26,403
37.211288
178
py
MaxStyle
MaxStyle-main/src/common_utils/load_model.py
import os from os.path import join import torch def resume_model_from_file(file_path): start_epoch = 1 optimizer_state = None state_dict = None checkpoint = None assert os.path.isfile(file_path) if '.pkl' in file_path: print("Loading models and optimizer from checkpoint '{}'".format(f...
1,776
33.843137
96
py
MaxStyle
MaxStyle-main/src/common_utils/basic_operations.py
# Created by cc215 at 27/12/19 # Enter feature description here # Enter scenario name here # Enter steps here from numpy.lib.function_base import copy import os import shutil import random import os import torch from torch._C import device import torch import random import numpy as np import SimpleITK as sitk import ...
11,521
32.300578
167
py
MaxStyle
MaxStyle-main/src/common_utils/vis.py
import numpy as np from PIL import Image import matplotlib.pyplot as plt from mpl_toolkits.axes_grid1.axes_divider import make_axes_locatable palette = [128, 64, 128, 244, 35, 232, 70, 70, 70, 102, 102, 156, 190, 153, 153, 153, 153, 153, 250, 170, 30, 220, 220, 0, 107, 142, 35, 152, 251, 152, 70, 130, 180, ...
5,867
30.891304
147
py
MaxStyle
MaxStyle-main/src/common_utils/save.py
import os import SimpleITK as sitk import numpy as np import matplotlib.pyplot as plt from PIL import Image from skimage.transform import resize import seaborn as sns from os.path import join import time import pickle import logging import torch import scipy.misc from src.common_utils.basic_operations import check_di...
13,492
34.885638
181
py
MaxStyle
MaxStyle-main/src/common_utils/metrics.py
# Adapted from score written by wkentaro # https://github.com/wkentaro/pytorch-fcn/blob/master/torchfcn/utils.py import numpy as np from medpy.metric.binary import dc import pandas as pd from IPython.display import display, HTML from src.common_utils.measure import hd, hd_2D_stack, asd, volumesimilarity, VolumeSimInd...
15,120
36.8025
152
py
MaxStyle
MaxStyle-main/src/common_utils/morphology.py
import math import pdb import torch import torch.nn as nn import torch.nn.functional as F class Morphology(nn.Module): ''' code is adapted from https://github.com/lc82111/pytorch_morphological_dilation2d_erosion2d/blob/master/morphology.py Base class for morpholigical operators For now, only supports...
4,149
37.425926
160
py
MaxStyle
MaxStyle-main/src/dataset_loader/cardiac_general_dataset.py
# Created by cc215 at 27/1/20 # this dataset is available at '/vol/medic01/users/cc215/data/MedicalDecathlon/Task05_Prostate/preprocessed' # from Medical Decathlon challenge dataset, we use T2 as input for the task. # Note: All images have been preprocessed (resampled to the 0.625 x 0.625 x 3.6 mm, the median value of ...
12,091
45.152672
195
py
MaxStyle
MaxStyle-main/src/dataset_loader/base_segmentation_dataset.py
# Created by cc215 at 11/12/19 # Enter feature description here # Enter scenario name here # Enter steps here import os import sys import torch.utils.data as data import torch from torch.utils.data import Dataset import random import numpy as np sys.path.append('../') from src.common_utils.basic_operations import swi...
19,478
37.802789
172
py
MaxStyle
MaxStyle-main/src/dataset_loader/generate_artefacted_data.py
import numpy as np import os from os.path import join import glob import matplotlib import matplotlib.pyplot as plt import torch import pandas as pd from random import randint import SimpleITK as sitk from torchio.transforms import RandomMotion, RandomSpike, RandomGhosting, RandomBiasField sys.path.append('../') from ...
4,393
38.232143
128
py
MaxStyle
MaxStyle-main/src/dataset_loader/prostate_Decathlon_dataset.py
# Created by cc215 at 27/1/20 # this dataset is available at '/vol/medic01/users/cc215/data/MedicalDecathlon/Task05_Prostate/preprocessed' # from Medical Decathlon challenge dataset, we use T2 as input for the task. # Note: All images have been preprocessed (resampled to the 0.625 x 0.625 x 3.6 mm, the median value of ...
12,452
46.530534
258
py
MaxStyle
MaxStyle-main/src/dataset_loader/transform.py
import torchsample.transforms as ts from src.dataset_loader._utils.affine_transform import MyRandomFlip, MySpecialCrop, MyPad, MyRandomChoiceRotate,MyRandomAffine from src.dataset_loader._utils.intensity_transform import RandomGamma, MyNormalizeMedicPercentile, MyRandomPurtarbation, MyRandomPurtarbationV2, RandomBright...
13,679
40.96319
172
py
MaxStyle
MaxStyle-main/src/dataset_loader/cardiac_ACDC_dataset.py
# Created by cc215 at 27/1/20 # this dataset is available at '/vol/medic01/users/cc215/Dropbox/projects/DeformADA/Data/ACDC' # from ACDC challenge dataset, containing ED/ES whole stack (3D). # Note: All images have been preprocessed and cropped to 224 by 224, following the preprocessing steps in # "Semi-Supervised and ...
11,085
46.174468
211
py
MaxStyle
MaxStyle-main/src/dataset_loader/_utils/elastic_transform.py
# Created by cc215 at 27/05/19 # perform elastic transform on 2D image data # for data augmentation # Enter steps here # Function to distort image import SimpleITK as sitk import numpy as np from scipy.ndimage.interpolation import map_coordinates from scipy.ndimage.filters import gaussian_filter from skimage import t...
7,216
40.716763
123
py
MaxStyle
MaxStyle-main/src/dataset_loader/_utils/affine_transform.py
import SimpleITK as sitk import torch from scipy import ndimage import math import cv2 import numpy as np from skimage import transform as sktform import torch as th from torch.autograd import Variable from skimage.exposure import equalize_adapthist from skimage.filters import gaussian import random from torchsample.ut...
30,417
36.004866
174
py
MaxStyle
MaxStyle-main/src/dataset_loader/_utils/intensity_transform.py
import numpy as np from skimage.exposure import equalize_adapthist import torch from scipy.ndimage import gaussian_filter import scipy import random import torch as th from PIL import Image from scipy.interpolate import RectBivariateSpline class MyRandomImageContrastTransform(object): def __init__(self, random_s...
23,854
42.531022
191
py
explainable-iqa
explainable-iqa-master/custom_gradcam.py
""" Created on Thu Oct 26 11:06:51 2017 @author: Utku Ozbulak - github.com/utkuozbulak @editor: Caner Ozer - github.com/canerozer """ import argparse import yaml import os import tqdm import numpy as np import pandas as pd from PIL import Image import torch import torch.nn as nn from torch.nn import Sequential from t...
16,845
38.731132
109
py
explainable-iqa
explainable-iqa-master/custom_normgrad.py
""" Created on Tue Sep 8 11:06:51 2020 @author: Sylvestre Rebuffi - github.com/srebuffi @editor: Caner Ozer - github.com/canerozer """ import argparse import yaml import os import tqdm import numpy as np import pandas as pd from PIL import Image from copy import deepcopy import torch import torch.nn as nn from torch....
14,594
39.654596
109
py
explainable-iqa
explainable-iqa-master/custom_guided_gradcam.py
""" Created on Thu Oct 23 11:27:15 2017 @author: Utku Ozbulak - github.com/utkuozbulak @editor: Caner Ozer - github.com/canerozer """ import argparse import yaml import os import tqdm import numpy as np import pandas as pd import torch from src.misc_functions import (get_example_params, convert_to_grayscale, ...
7,505
38.505263
109
py
explainable-iqa
explainable-iqa-master/custom_guided_backprop.py
""" Created on Thu Oct 26 11:23:47 2017 @author: Utku Ozbulak - github.com/utkuozbulak @editor: Caner Ozer - github.com/canerozer """ import argparse import yaml import os import tqdm import numpy as np import pandas as pd from PIL import Image import torch from torch.nn import ReLU, SiLU, Sequential from torchvision...
14,452
38.925414
109
py
explainable-iqa
explainable-iqa-master/custom_grad_times_image.py
""" Created on Wed Jun 19 17:12:04 2019 @author: Utku Ozbulak - github.com/utkuozbulak """ import argparse import yaml import os import tqdm import pandas as pd import torch from src.misc_functions import (get_example_params, convert_to_grayscale, preprocess_image, DictAsMember, ...
6,763
37.873563
109
py
explainable-iqa
explainable-iqa-master/src/guided_backprop.py
""" Created on Thu Oct 26 11:19:58 2017 @author: Utku Ozbulak - github.com/utkuozbulak @editor: Caner Ozer - github.com/canerozer """ import argparse import yaml import os import numpy as np from PIL import Image import torch from torch.nn import ReLU, Sequential from torchvision.models.resnet import BasicBlock, Bott...
4,286
34.139344
91
py
explainable-iqa
explainable-iqa-master/src/misc_functions.py
""" Created on Thu Oct 21 11:09:09 2017 @author: Utku Ozbulak - github.com/utkuozbulak @editor: Caner Ozer - github.com/canerozer """ import os import copy import math from functools import reduce import numpy as np import pandas as pd from PIL import Image, ImageFilter, UnidentifiedImageError, ImageDraw import matpl...
18,743
31.485269
91
py
explainable-iqa
explainable-iqa-master/src/normgrad.py
""" Created on Thu Oct 26 11:19:58 2017 @author: Utku Ozbulak - github.com/utkuozbulak @editor: Caner Ozer - github.com/canerozer """ import argparse import yaml import os import numpy as np from PIL import Image import torch import torch.nn.functional as F from torch.nn import Sequential from torchvision.models.resn...
5,405
38.459854
95
py
explainable-iqa
explainable-iqa-master/src/gradcam.py
""" Created on Thu Oct 26 11:19:58 2017 @author: Utku Ozbulak - github.com/utkuozbulak @editor: Caner Ozer - github.com/canerozer """ import argparse import yaml import os import numpy as np from PIL import Image import torch import torch.nn.functional as F from torch.nn import Sequential from torchvision.models.resn...
8,221
38.152381
98
py
explainable-iqa
explainable-iqa-master/src/backprop.py
""" Created on Thu Oct 26 11:19:58 2017 @author: Utku Ozbulak - github.com/utkuozbulak @editor: Caner Ozer - github.com/canerozer """ import argparse import yaml import os import numpy as np from PIL import Image import torch class VanillaBackprop(): """ Produces gradients generated with vanilla back pr...
1,757
28.3
81
py
explainable-iqa
explainable-iqa-master/src/pointing_game.py
r""" A Basic Implementation of the Pointing Game Some parts of these implementation were obtained from https://github.com/facebookresearch/TorchRay/blob/master/torchray/benchmark/pointing_game.py """ import random import numpy as np import pandas as pd from skimage.feature import peak_local_max class PointingGame:...
5,754
32.654971
92
py
explainable-iqa
explainable-iqa-master/src/models/__init__.py
import torch.nn as nn from torchvision import models as tvmodels def _get_classification_model(model_meta): name = model_meta.name n_classes = model_meta.n_classes pretrained = model_meta.pretrained model = None if name == "resnet18": model = tvmodels.resnet18(pretrained=pretrained) ...
961
32.172414
57
py
robbing_the_fed
robbing_the_fed-main/attacks/base_attack.py
"""Implementation for base attacker class. Inherit from this class for a consistent interface with attack cases.""" import torch from collections import defaultdict import copy from .common import optimizer_lookup import logging log = logging.getLogger(__name__) class _BaseAttacker: """This is a template cl...
16,305
48.865443
123
py
robbing_the_fed
robbing_the_fed-main/attacks/common.py
"""Common subfunctions to multiple modules.""" import torch def optimizer_lookup(params, optim_name, step_size, scheduler=None, warmup=0, max_iterations=10_000): if optim_name.lower() == "adam": optimizer = torch.optim.Adam(params, lr=step_size) elif optim_name.lower() == "momgd": optimizer ...
6,682
42.116129
152
py
robbing_the_fed
robbing_the_fed-main/attacks/analytic_attack.py
"""Simple analytic attack that works for (dumb) fully connected models.""" import torch from .base_attack import _BaseAttacker class AnalyticAttacker(_BaseAttacker): """Implements a sanity-check analytic inversion Only works for a torch.nn.Sequential model with input-sized FC layers.""" def __init__(s...
5,346
47.609091
111
py
robbing_the_fed
robbing_the_fed-main/modifications/imprint.py
"""Implements a malicious block that can be inserted at the front on normal models to break them.""" from statistics import NormalDist import torch import math from scipy.stats import laplace class ImprintBlock(torch.nn.Module): structure = "cumulative" def __init__(self, data_size, num_bins, connection="lin...
7,090
39.988439
122
py
robbing_the_fed
robbing_the_fed-main/utils/breaching_utils.py
from collections import namedtuple import torch def plot_data(cfg, user_data, setup, scale=False, print_labels=False): """Plot user data to output. Probably best called from a jupyter notebook.""" import matplotlib.pyplot as plt # lazily import this here dm = torch.as_tensor(cfg.mean, **setup)[None, :, N...
2,290
35.951613
99
py
robbing_the_fed
robbing_the_fed-main/utils/analysis.py
"""Simple report function based on PSNR and maybe SSIM and maybe better ideas...""" import torch from .metrics import psnr_compute, registered_psnr_compute, image_identifiability_precision #cw_ssim - can uncomment if you want ... import logging log = logging.getLogger(__name__) def report( reconstructed_user...
7,822
39.117949
119
py
robbing_the_fed
robbing_the_fed-main/utils/metrics.py
"""Various metrics.""" import torch from functools import partial def cw_ssim(img_batch, ref_batch, scales=5, skip_scales=None, K=1e-6): """Batched complex wavelet structural similarity. As in Zhou Wang and Eero P. Simoncelli, "TRANSLATION INSENSITIVE IMAGE SIMILARITY IN COMPLEX WAVELET DOMAIN" Ok, not q...
14,082
45.022876
122
py
BOCF
BOCF-master/doc/source/conf.py
# -*- coding: utf-8 -*- # # GPy documentation build configuration file, created by # sphinx-quickstart on Fri Sep 18 18:16:28 2015. # # 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. # # All c...
12,260
30.198473
113
py
numpy
numpy-main/numpy/core/_add_newdocs.py
""" This is only meant to add docs to objects defined in C-extension modules. The purpose is to allow easier editing of the docstrings without requiring a re-compile. NOTE: Many of the methods of ndarray have corresponding functions. If you update these docstrings, please keep also the ones in core/fromnum...
204,444
28.42925
128
py