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
BayesianRelevance
BayesianRelevance-master/src/attacks/deeprobust/other/BPDA.py
""" https://github.com/lordwarlock/Pytorch-BPDA/blob/master/bpda.py """ import torch import torch.nn as nn import torchvision.models as models import numpy as np def normalize(image, mean, std): return (image - mean)/std def preprocess(image): image = image / 255 image = np.transpose(image, (2, 0, 1)) ...
3,177
28.981132
117
py
BayesianRelevance
BayesianRelevance-master/src/attacks/deeprobust/other/onepixel.py
import numpy as np import argparse import torch import torch.nn as nn import torch.optim as optim import torch.nn.functional as F import torch.backends.cudnn as cudnn import torchvision import torchvision.transforms as transforms from torch.autograd import Variable from attacks.deeprobust.optimizer import different...
5,935
30.743316
149
py
BayesianRelevance
BayesianRelevance-master/src/attacks/deeprobust/other/l2_attack.py
import torch import torch.nn as nn import numpy as np import torch.nn.functional as F class CarliniL2: def __init__(self, model, device): self.model = model self.device = device def parse_params(self, gan, confidence=0, targeted=False, learning_rate=1e-1, binary_search_steps...
6,741
37.747126
97
py
BayesianRelevance
BayesianRelevance-master/src/plot/lrp_heatmaps.py
import os import lrp import copy import torch import numpy as np from tqdm import tqdm import matplotlib import pandas as pd import seaborn as sns import matplotlib.colors as colors import matplotlib.pyplot as plt from matplotlib.pyplot import cm from utils.savedir import * from utils.seeding import set_seed from uti...
17,425
41.502439
123
py
BayesianRelevance
BayesianRelevance-master/src/plot/attacks.py
import os import copy import numpy as np import matplotlib.pyplot as plt def plot_grid_attacks(original_images, perturbed_images, filename, savedir): fig, axes = plt.subplots(2, len(original_images), figsize = (12,4)) for i in range(0, len(original_images)): original_image = original_images[i].permu...
729
32.181818
123
py
BayesianRelevance
BayesianRelevance-master/src/plot/lrp_distributions.py
import os import lrp import copy import torch import matplotlib import numpy as np import pandas as pd import seaborn as sns from tqdm import tqdm from scipy import stats import matplotlib.colors as colors import matplotlib.pyplot as plt from matplotlib.pyplot import cm from utils.savedir import * from utils.seeding ...
39,083
43.718535
126
py
BayesianRelevance
BayesianRelevance-master/src/lrp/conv_cifar.py
import torch import torch.nn.functional as F from lrp.functional.conv_cifar import conv2d_cifar class Conv2d(torch.nn.Conv2d): def _conv_forward_explain(self, input, weight, conv2d_fn, **kwargs): if self.padding_mode != 'zeros': return conv2d_fn(F.pad(input, self._reversed_padding_repeated_twi...
1,390
42.46875
168
py
BayesianRelevance
BayesianRelevance-master/src/lrp/patterns.py
import torch import torch.nn.functional as F from .functional.utils import safe_divide from tqdm import tqdm __all__ = [ 'fit_patternnet', 'fit_patternnet_positive', ] """ This implementation is based on the implementation from https://github.com/albermax/innvestigate/blob/master/innvestigate/a...
4,582
29.758389
96
py
BayesianRelevance
BayesianRelevance-master/src/lrp/maxpool.py
import torch from lrp.functional import maxpool2d class MaxPool2d(torch.nn.MaxPool2d): def forward(self, input, explain=False, rule="epsilon", **kwargs): if not explain: return super(MaxPool2d, self).forward(input) return maxpool2d[rule](input, self.kernel_size, self.stride, self.padding)
311
38
82
py
BayesianRelevance
BayesianRelevance-master/src/lrp/sequential.py
import torch from lrp.linear import Linear from lrp.conv import Conv2d from lrp.maxpool import MaxPool2d from lrp.functional.utils import normalize def grad_decorator_fn(module): """ Currently not used but can be used for debugging purposes. """ def fn(x): return normalize(x) return fn...
1,789
30.403509
91
py
BayesianRelevance
BayesianRelevance-master/src/lrp/linear.py
import torch from lrp.functional import linear class Linear(torch.nn.Linear): def forward(self, input, explain=False, rule="epsilon", **kwargs): if not explain: return super(Linear, self).forward(input) p = kwargs.get('pattern') if p is not None: return linear[rule](input, self.weight, sel...
644
32.947368
91
py
BayesianRelevance
BayesianRelevance-master/src/lrp/converter.py
import torch from .conv import Conv2d from .linear import Linear from .sequential import Sequential conversion_table = { 'Linear': Linear, 'Conv2d': Conv2d } # # # # # Convert torch.models.vggxx to lrp model def convert_vgg(module, modules=None): # First time if modules is None...
1,436
30.23913
84
py
BayesianRelevance
BayesianRelevance-master/src/lrp/conv.py
import torch import torch.nn.functional as F from lrp.functional import conv2d class Conv2d(torch.nn.Conv2d): def _conv_forward_explain(self, input, weight, conv2d_fn, **kwargs): if self.padding_mode != 'zeros': return conv2d_fn(F.pad(input, self._reversed_padding_repeated_twice, mode=self.pad...
1,367
41.75
168
py
BayesianRelevance
BayesianRelevance-master/src/lrp/functional/conv_cifar.py
import torch import torch.nn.functional as F from torch.autograd import Function from .utils import identity_fn, gamma_fn, add_epsilon_fn, normalize def _forward_rho(rho, incr, ctx, input, weight, bias, stride, padding, dilation, groups): ctx.save_for_backward(input, weight, bias) ctx.rho = rho ...
6,354
37.98773
126
py
BayesianRelevance
BayesianRelevance-master/src/lrp/functional/maxpool.py
import torch import torch.nn.functional as F from torch.autograd import Function class MaxPooling2d(Function): @staticmethod def forward(ctx, input, kernel_size=2, stride=None, padding=0): ctx.kernel_size = kernel_size ctx.stride = stride ctx.padding = padding ctx.save...
1,398
36.810811
108
py
BayesianRelevance
BayesianRelevance-master/src/lrp/functional/utils.py
import torch # # # rhos identity_fn = lambda w, b: (w, b) def gamma_fn(gamma): def _gamma_fn(w, b): w = w + w * torch.max(torch.tensor(0., device=w.device), w) * gamma if b is not None: b = b + b * torch.max(torch.tensor(0., device=b.device), b) * gamma return w, b return _gamma_f...
981
24.842105
120
py
BayesianRelevance
BayesianRelevance-master/src/lrp/functional/linear.py
import torch import torch.nn.functional as F from torch.autograd import Function from .utils import identity_fn, gamma_fn, add_epsilon_fn, normalize def _forward_rho(rho, incr, ctx, input, weight, bias): ctx.save_for_backward(input, weight, bias) ctx.rho = rho ctx.incr = incr return F.linear(input, we...
5,193
32.509677
167
py
BayesianRelevance
BayesianRelevance-master/src/lrp/functional/__init__.py
from .conv import conv2d from .linear import linear from .maxpool import maxpool2d __all__ = [ 'maxpool2d', 'conv2d', 'linear', ]
170
16.1
32
py
BayesianRelevance
BayesianRelevance-master/src/lrp/functional/conv.py
import torch import torch.nn.functional as F from torch.autograd import Function from .utils import identity_fn, gamma_fn, add_epsilon_fn, normalize def _forward_rho(rho, incr, ctx, input, weight, bias, stride, padding, dilation, groups): ctx.save_for_backward(input, weight, bias) ctx.rho = rho ...
6,341
37.907975
126
py
BayesianRelevance
BayesianRelevance-master/src/utils/model_settings.py
""" Architectures and parameters """ baseNN_settings = {"model_0":{"dataset":"mnist", "hidden_size":512, "activation":"leaky", "architecture":"conv", "epochs":5, "lr":0.001}, "model_1":{"dataset":"fashion_mnist", "hidden_size":1024, "activation":"leaky", ...
2,311
78.724138
123
py
BayesianRelevance
BayesianRelevance-master/src/utils/data.py
import os import math import time import random import numpy as np import pickle as pkl from utils.savedir import * import torch import keras import tensorflow as tf from keras import backend as K from keras.datasets import mnist, fashion_mnist from sklearn.datasets import make_moons from pandas import DataFrame from ...
12,410
34.766571
116
py
BayesianRelevance
BayesianRelevance-master/src/utils/networks.py
import torch import torch.nn as nn def relu_to_softplus(model, beta): for child_name, child in model.named_children(): if isinstance(child, nn.LeakyReLU): setattr(model, child_name, nn.Softplus(beta=beta)) else: relu_to_softplus(child, beta) return model def change_beta(model, beta): for child_name, ch...
492
22.47619
53
py
BayesianRelevance
BayesianRelevance-master/src/utils/seeding.py
import torch import numpy as np import random import pyro def set_seed(seed): torch.manual_seed(seed) torch.cuda.manual_seed(seed) torch.cuda.manual_seed_all(seed) np.random.seed(seed) random.seed(seed) pyro.set_rng_seed(seed) set_seed(0)
267
14.764706
36
py
BayesianRelevance
BayesianRelevance-master/src/utils/savedir.py
import os import sys import time DATA = "../data/" TESTS = "../experiments/" ATK_DIR = "attacks/" def get_model_savedir(model, dataset, architecture, iters=None, inference=None, baseiters=None, model_idx=None, layer_idx=None, debug=False, torchvision=False, attack_method=None): if torchvis...
2,068
28.557143
106
py
BayesianRelevance
BayesianRelevance-master/src/utils/lrp.py
import os import lrp import copy import torch import numpy as np from torch import nn from tqdm import tqdm import torch.nn.functional as nnf from torchvision import transforms from scipy.stats import wasserstein_distance from utils.savedir import * from utils.seeding import set_seed from utils.data import load_from_p...
8,089
28.418182
129
py
BayesianRelevance
BayesianRelevance-master/src/bayesian_torch/bayesian_torch/__init__.py
0
0
0
py
BayesianRelevance
BayesianRelevance-master/src/bayesian_torch/bayesian_torch/examples/main_bayesian_flipout_cifar.py
import argparse import os import shutil import time import torch import torch.nn as nn import torch.nn.parallel import torch.backends.cudnn as cudnn import torch.optim import torch.utils.data from torch.utils.tensorboard import SummaryWriter import torchvision.transforms as transforms import torchvision.datasets as da...
18,058
32.881801
111
py
BayesianRelevance
BayesianRelevance-master/src/bayesian_torch/bayesian_torch/examples/main_deterministic_cifar.py
import argparse import os import shutil import time import torch import torch.nn as nn import torch.nn.parallel import torch.backends.cudnn as cudnn import torch.optim import torch.utils.data from torch.utils.tensorboard import SummaryWriter import torchvision.transforms as transforms import torchvision.datasets as da...
15,192
32.100218
78
py
BayesianRelevance
BayesianRelevance-master/src/bayesian_torch/bayesian_torch/examples/main_bayesian_cifar.py
import argparse import os import shutil import time import torch import torch.nn as nn import torch.nn.parallel import torch.backends.cudnn as cudnn import torch.optim import torch.utils.data # from torch.utils.tensorboard import SummaryWriter import torchvision.transforms as transforms import torchvision.datasets as ...
24,193
33.31773
122
py
BayesianRelevance
BayesianRelevance-master/src/bayesian_torch/bayesian_torch/examples/main_bayesian_imagenet.py
''' code adapted from PyTorch examples ''' import argparse import os import random import shutil import time import warnings import torch import torch.nn as nn import torch.nn.parallel import torch.backends.cudnn as cudnn import torch.distributed as dist import torch.optim import torch.multiprocessing as mp import tor...
26,624
36.082173
110
py
BayesianRelevance
BayesianRelevance-master/src/bayesian_torch/bayesian_torch/examples/main_bayesian_flipout_imagenet.py
''' code adapted from PyTorch examples ''' import argparse import os import random import shutil import time import warnings import torch import torch.nn as nn import torch.nn.parallel import torch.backends.cudnn as cudnn import torch.distributed as dist import torch.optim import torch.multiprocessing as mp import tor...
26,792
36.472727
114
py
BayesianRelevance
BayesianRelevance-master/src/bayesian_torch/bayesian_torch/examples/main_deterministic_imagenet.py
''' code adapted from PyTorch examples ''' import argparse import os import random import shutil import time import warnings import torch import torch.nn as nn import torch.nn.parallel import torch.backends.cudnn as cudnn import torch.distributed as dist import torch.optim import torch.multiprocessing as mp import tor...
20,770
34.264856
110
py
BayesianRelevance
BayesianRelevance-master/src/bayesian_torch/bayesian_torch/examples/main_deterministic_mnist.py
from __future__ import print_function import os import argparse import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim from torchvision import datasets, transforms from torch.optim.lr_scheduler import StepLR from torch.utils.tensorboard import SummaryWriter import numpy as np im...
7,802
36.157143
79
py
BayesianRelevance
BayesianRelevance-master/src/bayesian_torch/bayesian_torch/examples/main_bayesian_mnist.py
from __future__ import print_function import os import argparse import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim from torchvision import datasets, transforms from torch.optim.lr_scheduler import StepLR from torch.utils.tensorboard import SummaryWriter import numpy as np imp...
9,196
35.208661
79
py
BayesianRelevance
BayesianRelevance-master/src/bayesian_torch/bayesian_torch/models/__init__.py
0
0
0
py
BayesianRelevance
BayesianRelevance-master/src/bayesian_torch/bayesian_torch/models/flipout/resnet.py
0
0
0
py
BayesianRelevance
BayesianRelevance-master/src/bayesian_torch/bayesian_torch/models/flipout/simple_cnn.py
from __future__ import print_function import argparse import torch import torch.nn as nn import torch.nn.functional as F from bayesian_torch.layers import Conv2dFlipout from bayesian_torch.layers import LinearFlipout prior_mu = 0 prior_sigma = 0.05 posterior_mu_init = 0 posterior_rho_init = -7.0 #-6.0 class SCNN(n...
2,267
28.842105
71
py
BayesianRelevance
BayesianRelevance-master/src/bayesian_torch/bayesian_torch/models/flipout/__init__.py
0
0
0
py
BayesianRelevance
BayesianRelevance-master/src/bayesian_torch/bayesian_torch/models/deterministic/resnet.py
''' ResNet for CIFAR10. Ref: [1] Kaiming He, Xiangyu Zhang, Shaoqing Ren, Jian Sun Deep Residual Learning for Image Recognition. arXiv:1512.03385 ''' import torch import torch.nn as nn import torch.nn.functional as F import torch.nn.init as init from lrp.linear import Linear from lrp.conv_cifar import Conv2d from...
4,977
29.539877
76
py
BayesianRelevance
BayesianRelevance-master/src/bayesian_torch/bayesian_torch/models/deterministic/resnet_large.py
# ResNet for ImageNet # ResNet architecture ref: # https://arxiv.org/abs/1512.03385 # Code from torchvision package import torch.nn as nn import math import torch.utils.model_zoo as model_zoo __all__ = [ 'ResNet', 'resnet18', 'resnet34', 'resnet50', 'resnet101', 'resnet152' ] model_urls = { 'resnet18': 'http...
7,104
29.625
78
py
BayesianRelevance
BayesianRelevance-master/src/bayesian_torch/bayesian_torch/models/deterministic/simple_cnn.py
from __future__ import print_function import argparse import torch import torch.nn as nn import torch.nn.functional as F class SCNN(nn.Module): def __init__(self): super(SCNN, self).__init__() self.conv1 = nn.Conv2d(1, 32, 3, 1) self.conv2 = nn.Conv2d(32, 64, 3, 1) self.dropout1 = ...
836
25.15625
44
py
BayesianRelevance
BayesianRelevance-master/src/bayesian_torch/bayesian_torch/models/deterministic/__init__.py
0
0
0
py
BayesianRelevance
BayesianRelevance-master/src/bayesian_torch/bayesian_torch/models/bayesian/resnet_flipout.py
''' Bayesian ResNet with Flipout Monte Carlo estimator for CIFAR10. Ref: ResNet architecture: [1] Kaiming He, Xiangyu Zhang, Shaoqing Ren, Jian Sun Deep Residual Learning for Image Recognition. arXiv:1512.03385 Flipout: [2] Wen, Yeming, et al. "Flipout: Efficient Pseudo-Independent Weight Perturbations on Mi...
5,606
28.356021
77
py
BayesianRelevance
BayesianRelevance-master/src/bayesian_torch/bayesian_torch/models/bayesian/resnet_variational.py
''' Bayesian ResNet for CIFAR10. ResNet architecture ref: [1] Kaiming He, Xiangyu Zhang, Shaoqing Ren, Jian Sun Deep Residual Learning for Image Recognition. arXiv:1512.03385 ''' import torch import torch.nn as nn import torch.nn.functional as F import torch.nn.init as init from bayesian_torch.bayesian_torch.laye...
6,935
30.103139
116
py
BayesianRelevance
BayesianRelevance-master/src/bayesian_torch/bayesian_torch/models/bayesian/resnet_flipout_large.py
# Bayesian ResNet for ImageNet # ResNet architecture ref: # https://arxiv.org/abs/1512.03385 # Code adapted from torchvision package to build Bayesian model from deterministic model import torch.nn as nn import math import torch.utils.model_zoo as model_zoo import torch.nn as nn import torch.nn.functional as F import ...
10,869
33.507937
88
py
BayesianRelevance
BayesianRelevance-master/src/bayesian_torch/bayesian_torch/models/bayesian/__init__.py
0
0
0
py
BayesianRelevance
BayesianRelevance-master/src/bayesian_torch/bayesian_torch/models/bayesian/resnet_variational_large.py
# Bayesian ResNet for ImageNet # ResNet architecture ref: # https://arxiv.org/abs/1512.03385 # Code adapted from torchvision package to build Bayesian model from deterministic model import torch.nn as nn import math import torch.utils.model_zoo as model_zoo import torch.nn as nn import torch.nn.functional as F import ...
10,428
31.590625
88
py
BayesianRelevance
BayesianRelevance-master/src/bayesian_torch/bayesian_torch/models/bayesian/simple_cnn_variational.py
from __future__ import print_function import argparse import torch import torch.nn as nn import torch.nn.functional as F from bayesian_torch.layers import Conv2dReparameterization from bayesian_torch.layers import LinearReparameterization prior_mu = 0.0 prior_sigma = 1.0 posterior_mu_init = 0.0 posterior_rho_init = -...
2,246
27.443038
58
py
BayesianRelevance
BayesianRelevance-master/src/bayesian_torch/bayesian_torch/layers/batchnorm.py
''' wrapper for Batch Normalization layers ''' import torch import torch.nn as nn from torch.nn import Parameter import torch.nn.functional as F class BatchNorm2dLayer(nn.Module): def __init__(self, num_features, eps=1e-5, momentum=0.1, affine=Tr...
7,672
37.365
78
py
BayesianRelevance
BayesianRelevance-master/src/bayesian_torch/bayesian_torch/layers/base_variational_layer.py
# Copyright (C) 2021 Intel Labs # # BSD-3-Clause License # # Redistribution and use in source and binary forms, with or without modification, # are permitted provided that the following conditions are met: # 1. Redistributions of source code must retain the above copyright notice, # this list of conditions and the f...
2,497
45.259259
97
py
BayesianRelevance
BayesianRelevance-master/src/bayesian_torch/bayesian_torch/layers/dropout.py
''' wrapper for Dropout ''' import torch import torch.nn as nn from torch.nn import Parameter import torch.nn.functional as F class Dropout(nn.Module): __constants__ = ['p', 'inplace'] def __init__(self, p=0.5, inplace=False): super(Dropout, self).__init__() if p < 0 or p > 1: r...
703
23.275862
76
py
BayesianRelevance
BayesianRelevance-master/src/bayesian_torch/bayesian_torch/layers/__init__.py
from .flipout_layers import * from .variational_layers import * from .base_variational_layer import * from .batchnorm import * from .dropout import * from .relu import *
170
23.428571
37
py
BayesianRelevance
BayesianRelevance-master/src/bayesian_torch/bayesian_torch/layers/relu.py
''' wrapper for ReLU ''' import torch import torch.nn as nn from torch.nn import Parameter import torch.nn.functional as F class ReLU(nn.Module): __constants__ = ['inplace'] def __init__(self, inplace=False): super(ReLU, self).__init__() self.inplace = inplace def forward(self, input): ...
508
19.36
60
py
BayesianRelevance
BayesianRelevance-master/src/bayesian_torch/bayesian_torch/layers/variational_layers/linear_variational.py
# Copyright (C) 2021 Intel Labs # # BSD-3-Clause License # # Redistribution and use in source and binary forms, with or without modification, # are permitted provided that the following conditions are met: # 1. Redistributions of source code must retain the above copyright notice, # this list of conditions and the ...
7,337
46.341935
148
py
BayesianRelevance
BayesianRelevance-master/src/bayesian_torch/bayesian_torch/layers/variational_layers/conv_variational.py
# Copyright (C) 2021 Intel Labs # # BSD-3-Clause License # # Redistribution and use in source and binary forms, with or without modification, # are permitted provided that the following conditions are met: # 1. Redistributions of source code must retain the above copyright notice, # this list of conditions and the ...
38,039
44.231867
148
py
BayesianRelevance
BayesianRelevance-master/src/bayesian_torch/bayesian_torch/layers/variational_layers/__init__.py
from .linear_variational import * from .conv_variational import * from .rnn_variational import *
97
23.5
33
py
BayesianRelevance
BayesianRelevance-master/src/bayesian_torch/bayesian_torch/layers/variational_layers/rnn_variational.py
# Copyright (C) 2021 Intel Labs # # BSD-3-Clause License # # Redistribution and use in source and binary forms, with or without modification, # are permitted provided that the following conditions are met: # 1. Redistributions of source code must retain the above copyright notice, # this list of conditions and the ...
5,973
40.486111
121
py
BayesianRelevance
BayesianRelevance-master/src/bayesian_torch/bayesian_torch/layers/flipout_layers/linear_flipout.py
# Copyright (C) 2021 Intel Labs # # BSD-3-Clause License # # Redistribution and use in source and binary forms, with or without modification, # are permitted provided that the following conditions are met: # 1. Redistributions of source code must retain the above copyright notice, # this list of conditions and the f...
6,701
43.979866
148
py
BayesianRelevance
BayesianRelevance-master/src/bayesian_torch/bayesian_torch/layers/flipout_layers/rnn_flipout.py
# Copyright (C) 2021 Intel Labs # # BSD-3-Clause License # # Redistribution and use in source and binary forms, with or without modification, # are permitted provided that the following conditions are met: # 1. Redistributions of source code must retain the above copyright notice, # this list of conditions and the f...
6,145
42.588652
148
py
BayesianRelevance
BayesianRelevance-master/src/bayesian_torch/bayesian_torch/layers/flipout_layers/__init__.py
from .conv_flipout import * from .linear_flipout import * from .rnn_flipout import *
85
20.5
29
py
BayesianRelevance
BayesianRelevance-master/src/bayesian_torch/bayesian_torch/layers/flipout_layers/conv_flipout.py
# Copyright (C) 2021 Intel Labs # # BSD-3-Clause License # # Redistribution and use in source and binary forms, with or without modification, # are permitted provided that the following conditions are met: # 1. Redistributions of source code must retain the above copyright notice, # this list of conditions and the f...
39,426
42.042576
148
py
BayesianRelevance
BayesianRelevance-master/src/bayesian_torch/bayesian_torch/utils/util.py
# Copyright (C) 2021 Intel Labs # # BSD-3-Clause License # # Redistribution and use in source and binary forms, with or without modification, # are permitted provided that the following conditions are met: # 1. Redistributions of source code must retain the above copyright notice, # this list of conditions and the ...
5,400
41.195313
98
py
BayesianRelevance
BayesianRelevance-master/src/bayesian_torch/bayesian_torch/utils/__init__.py
0
0
0
py
ssl-torch
ssl-torch-main/transform.py
import numpy as np import torch from scipy import signal import math import cv2 import random class Transform: def __init__(self): pass def add_noise(self, signal, noise_amount): """ adding noise """ signal = signal.T noise = (0.4 ** 0.5) * np.random.normal(...
9,975
34.884892
103
py
ssl-torch
ssl-torch-main/contrast.py
from net import resnet18, resnet34, resnet50, resnet101, resnet152 import torch import torch.nn as nn import numpy as np # import pandas as pd import tqdm import mit_utils as utils # import analytics import time import os, shutil from mail import mail_it from sklearn.metrics import confusion_matrix from sklearn.metric...
12,884
30.274272
111
py
ssl-torch
ssl-torch-main/net.py
import torch import torch.nn as nn import math import torch.utils.model_zoo as model_zoo __all__ = ['ResNet', 'resnet18', 'resnet34', 'resnet50', 'resnet101', 'resnet152'] model_urls = { 'resnet18': 'https://download.pytorch.org/models/resnet18-5c106cde.pth', 'resnet34': 'https://download.pytorch....
8,532
32.073643
98
py
ssl-torch
ssl-torch-main/mit_utils.py
# -*- coding: utf-8 -*- """ Created on Thu Mar 14 23:47:38 2019 @author: Winham 辅助函数 """ import warnings import numpy as np from scipy.signal import resample # import pywt from sklearn.preprocessing import scale from sklearn.metrics import confusion_matrix from sklearn.metrics import accuracy_score from sklearn.util...
4,714
29.031847
156
py
bert-extractive-summarizer
bert-extractive-summarizer-master/setup.py
from setuptools import setup from setuptools import find_packages setup(name='bert-extractive-summarizer', version='0.10.1', description='Extractive Text Summarization with BERT', keywords=['bert', 'pytorch', 'machine learning', 'deep learning', 'extractive summarization', 'summary'],...
833
42.894737
101
py
bert-extractive-summarizer
bert-extractive-summarizer-master/server.py
from flask import Flask from flask import request, jsonify, abort, make_response from flask_cors import CORS import nltk nltk.download('punkt') from nltk import tokenize from typing import List import argparse from summarizer import Summarizer, TransformerSummarizer app = Flask(__name__) CORS(app) class Parser(obje...
4,393
32.8
113
py
bert-extractive-summarizer
bert-extractive-summarizer-master/examples/summarize.py
from summarizer import Summarizer import argparse def run(): parser = argparse.ArgumentParser(description='Process and summarize lectures') parser.add_argument('-path', dest='path', default=None, help='File path of lecture') parser.add_argument('-model', dest='model', default='bert-large-uncased', help=''...
1,036
31.40625
128
py
bert-extractive-summarizer
bert-extractive-summarizer-master/summarizer/bert.py
from functools import partial from typing import List, Optional, Union from transformers import (AlbertModel, AlbertTokenizer, BartModel, BigBirdModel, BigBirdTokenizer, BartTokenizer, BertModel, BertTokenizer, CamembertModel, CamembertTokenizer, CTRLModel, ...
7,082
47.183673
120
py
bert-extractive-summarizer
bert-extractive-summarizer-master/summarizer/summary_processor.py
from typing import Callable, List, Optional, Tuple, Union import numpy as np from summarizer.cluster_features import ClusterFeatures from summarizer.text_processors.sentence_handler import SentenceHandler from summarizer.util import AGGREGATE_MAP class SummaryProcessor: """General Summarizer Parent for all clus...
8,794
36.109705
110
py
bert-extractive-summarizer
bert-extractive-summarizer-master/summarizer/sbert.py
from summarizer.summary_processor import SummaryProcessor from summarizer.text_processors.sentence_handler import SentenceHandler from summarizer.transformer_embeddings.sbert_embedding import SBertEmbedding class SBertSummarizer(SummaryProcessor): """ The SBert Summarizer. This is based on the Sentence B...
992
32.1
110
py
bert-extractive-summarizer
bert-extractive-summarizer-master/summarizer/util.py
import numpy as np AGGREGATE_MAP = { 'mean': np.mean, 'min': np.min, 'median': np.median, 'max': np.max, }
124
12.888889
24
py
bert-extractive-summarizer
bert-extractive-summarizer-master/summarizer/__init__.py
from summarizer.bert import Summarizer, TransformerSummarizer __all__ = ["Summarizer", "TransformerSummarizer"]
113
27.5
61
py
bert-extractive-summarizer
bert-extractive-summarizer-master/summarizer/cluster_features.py
from typing import Dict, List, Union import numpy as np from numpy import ndarray from sklearn.cluster import KMeans from sklearn.decomposition import PCA from sklearn.mixture import GaussianMixture class ClusterFeatures: """Basic handling of clustering features.""" def __init__( self, featu...
4,938
28.753012
100
py
bert-extractive-summarizer
bert-extractive-summarizer-master/summarizer/text_processors/sentence_abc.py
from typing import List from spacy.language import Language class SentenceABC: """Parent Class for sentence processing.""" def __init__(self, nlp: Language, is_spacy_3: bool): """ Base Sentence Handler with Spacy support. :param nlp: NLP Pipeline. :param is_spacy_3: Whether ...
2,106
30.447761
84
py
bert-extractive-summarizer
bert-extractive-summarizer-master/summarizer/text_processors/sentence_handler.py
from typing import List from spacy.lang.en import English from spacy.language import Language from summarizer.text_processors.sentence_abc import SentenceABC class SentenceHandler(SentenceABC): """Basic Sentence Handler.""" def __init__(self, language: Language = English): """ Base Sentence ...
1,266
28.465116
71
py
bert-extractive-summarizer
bert-extractive-summarizer-master/summarizer/text_processors/__init__.py
0
0
0
py
bert-extractive-summarizer
bert-extractive-summarizer-master/summarizer/text_processors/coreference_handler.py
# removed previous import and related functionality since it's just a blank language model, # while neuralcoref requires passing pretrained language model via spacy.load() from typing import List import neuralcoref import spacy from summarizer.text_processors.sentence_abc import SentenceABC class CoreferenceHandl...
1,430
33.071429
91
py
bert-extractive-summarizer
bert-extractive-summarizer-master/summarizer/transformer_embeddings/bert_embedding.py
from typing import List, Union import numpy as np import torch from numpy import ndarray from transformers import (AlbertModel, AlbertTokenizer, BertModel, BertTokenizer, DistilBertModel, DistilBertTokenizer, PreTrainedModel, PreTrainedTokenizer, XLMModel, ...
6,387
35.712644
114
py
bert-extractive-summarizer
bert-extractive-summarizer-master/summarizer/transformer_embeddings/sbert_embedding.py
from typing import List import numpy as np import torch from sentence_transformers import SentenceTransformer class SBertEmbedding: """SBert Embedding. This is for the SentenceTransformer Package.""" def __init__(self, model: str): """ SBert Parent Handler. :param model: The model s...
1,129
27.974359
82
py
bert-extractive-summarizer
bert-extractive-summarizer-master/summarizer/transformer_embeddings/__init__.py
0
0
0
py
bert-extractive-summarizer
bert-extractive-summarizer-master/tests/test_summary_items.py
import pytest import torch from transformers import AlbertTokenizer, AlbertModel from summarizer import Summarizer, TransformerSummarizer @pytest.fixture() def custom_summarizer(): albert_model = AlbertModel.from_pretrained('albert-base-v2', output_hidden_states=True) albert_tokenizer = AlbertTokenizer.from_...
7,139
46.6
424
py
bert-extractive-summarizer
bert-extractive-summarizer-master/tests/test_sentence_handler.py
import pytest from summarizer.text_processors.sentence_handler import SentenceHandler @pytest.fixture() def sentence_handler(): return SentenceHandler() @pytest.fixture() def passage(): return ''' The Chrysler Building, the famous art deco New York skyscraper, will be sold for a small fraction of its p...
3,186
73.116279
383
py
bert-extractive-summarizer
bert-extractive-summarizer-master/tests/test_sbert.py
import pytest from summarizer.sbert import SBertSummarizer from summarizer.text_processors.sentence_handler import SentenceHandler @pytest.fixture() def passage(): return ''' The Chrysler Building, the famous art deco New York skyscraper, will be sold for a small fraction of its previous sales price. The...
5,169
55.813187
545
py
bert-extractive-summarizer
bert-extractive-summarizer-master/tests/test_coreference.py
import pytest from summarizer.text_processors.coreference_handler import CoreferenceHandler @pytest.fixture() def coreference_handler(): return CoreferenceHandler() def test_coreference_handler(coreference_handler): orig = '''My sister has a dog. She loves him.''' resolved = '''My sister has a dog. My ...
444
26.8125
77
py
bert-extractive-summarizer
bert-extractive-summarizer-master/tests/__init__.py
0
0
0
py
FreeSolv
FreeSolv-master/scripts/generate-tripos-mol2files.py
""" Generate Tripos mol2 files with AM1-BCC charges from canonical isomeric SMILES strings. Molecules will be named after database key. """ import os from openeye import oechem from openeye import oeiupac from openeye import oeomega from openeye import oequacpac import utils def generate_molecule_from_smiles(smil...
4,251
28.943662
143
py
FreeSolv
FreeSolv-master/scripts/make_supporting_files.py
#!/bin/env python import pickle import utils file = open('../database.pickle', 'rb') database = pickle.load(file, encoding='latin1') file.close() utils.convert_to_json('../database.pickle', '../database.json') #Put it in a nice table for easy parsing. Use semicolons to separate fields, making sure each individual fi...
3,112
39.960526
393
py
FreeSolv
FreeSolv-master/scripts/make_v0.32.py
#!/bin/env python """Make edits to database for v0.32 release - specifically, fixing some issues relating to two nitro compounds which had incorrect SMILES.""" #Load database import pickle file = open('../database.pickle', 'r') database = pickle.load(file) file.close() #Fix SMILES for mobley_3802803 database['mobley...
943
28.5
141
py
FreeSolv
FreeSolv-master/scripts/utils.py
""" Shared utilities. """ #import cPickle as pickle import pickle from openeye.oechem import * def read_database(): """Read the database from a pickle file and return it""" database_filename = 'database.pickle' with open(database_filename, 'rb') as database_file: database = pickle.load(database_f...
1,907
25.5
91
py
FreeSolv
FreeSolv-master/scripts/rebuild_freesolv.py
#!/usr/bin/env python """ Use the openmoltools wrappers of OpenEye and Antechamber to rebuild input files for the FreeSolv database. Looks for freesolve database using environment variable FREESOLV_PATH Outputs two LOCAL directories of files: ./tripos_mol2/ and ./mol2files_gaff/ """ import os import openmoltools impor...
2,555
43.842105
181
py
FreeSolv
FreeSolv-master/scripts/extract-primary-data.py
""" Extract the primary data from the original database pickle file. Primary data is defined as: - canonical isomeric SMILES all match - experimental data: + experimental value + experiemntal uncertainty + citation for experimental data - notes field - nickname field Example entry: {'smiles': 'CCc1cccc2c1cccc2...
1,665
36.022222
370
py
FreeSolv
FreeSolv-master/scripts/make_v0.52.py
#!/bin/env python """This will update the current v0.51 database to v0.52 to reflect the following changes: - Update DOI for all calculated values to 2017 J Chem Eng Data paper associated with v0.51 (10.1021/acs.jced.7b00104) - Remove duplicate compound mobley_4689084, which was a SAMPL1 compound that was already pres...
1,663
45.222222
565
py
FreeSolv
FreeSolv-master/scripts/hComponents.py
#!/usr/bin/env python import os, pickle, glob, sys import numpy as np from pymbar.timeseries import statisticalInefficiency def doStatistics( filename ): array = np.genfromtxt( filename, skip_header = 100 , usecols = 1, dtype = float) return np.mean(array), np.std(array) / np.sqrt(len(array)/statisticalIneffic...
2,365
35.4
111
py
probdet
probdet-master/src/single_image_inference.py
""" Probabilistic Detectron Single Image Inference Script """ import core import cv2 import json import os import sys import torch import tqdm # This is very ugly. Essential for now but should be fixed. sys.path.append(os.path.join(core.top_dir(), 'src', 'detr')) # Detectron imports from detectron2.engine import laun...
4,579
34.78125
104
py
probdet
probdet-master/src/apply_net.py
""" Probabilistic Detectron Inference Script """ import core import json import os import sys import torch import tqdm from shutil import copyfile # This is very ugly. Essential for now but should be fixed. sys.path.append(os.path.join(core.top_dir(), 'src', 'detr')) # Detectron imports from detectron2.engine import ...
4,133
33.45
150
py
probdet
probdet-master/src/__init__.py
0
0
0
py
probdet
probdet-master/src/train_net.py
""" Probabilistic Detectron Training Script following Detectron2 training script found at detectron2/tools. """ import core import os import sys # This is very ugly. Essential for now but should be fixed. sys.path.append(os.path.join(core.top_dir(), 'src', 'detr')) # Detectron imports import detectron2.utils.comm as ...
3,264
27.391304
103
py