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 |
|---|---|---|---|---|---|---|
CognitiveDistillation | CognitiveDistillation-main/datasets/cifar_fc.py | import torch
import numpy as np
from torchvision import datasets
if torch.cuda.is_available():
device = torch.device('cuda')
else:
device = torch.device('cpu')
class FCCIFAR10(datasets.CIFAR10):
def __init__(self, root, train=True, transform=None, target_transform=None,
download=False, p... | 2,051 | 40.04 | 101 | py |
CognitiveDistillation | CognitiveDistillation-main/datasets/cifar_dfst.py | import torch
import numpy as np
import pickle
from torchvision import datasets
if torch.cuda.is_available():
device = torch.device('cuda')
else:
device = torch.device('cpu')
class DFSTCIFAR10(datasets.CIFAR10):
def __init__(self, root, train=True, transform=None, target_transform=None,
d... | 1,609 | 34.777778 | 101 | py |
CognitiveDistillation | CognitiveDistillation-main/datasets/utils.py | import os
import torch
import numpy as np
from torchvision import transforms
from torchvision.datasets import CIFAR10, CIFAR100, SVHN, MNIST, ImageNet, GTSRB
from torchvision.datasets.folder import ImageFolder
from .cifar_custom import CustomCIFAR10
from .cifar_badnet import BadNetCIFAR10
from .cifar_sig import SIGCIFA... | 11,124 | 42.287938 | 118 | py |
CognitiveDistillation | CognitiveDistillation-main/datasets/dataset.py | import numpy as np
from .utils import transform_options, dataset_options
from torch.utils.data import DataLoader
from torchvision import transforms
class DatasetGenerator():
def __init__(self, exp, train_bs=128, eval_bs=256, seed=0, n_workers=4,
train_d_type='CIFAR10', test_d_type='CIFAR10',
... | 3,965 | 49.202532 | 100 | py |
CognitiveDistillation | CognitiveDistillation-main/datasets/gtsrb_badnet.py | import torch
import numpy as np
import PIL
from torchvision import datasets
from torchvision import transforms
if torch.cuda.is_available():
device = torch.device('cuda')
else:
device = torch.device('cpu')
class BadNetGTSRB(datasets.GTSRB):
def __init__(self, root, split='train', transform=None, target_t... | 2,265 | 36.147541 | 101 | py |
CognitiveDistillation | CognitiveDistillation-main/datasets/cifar_sig.py | import torch
import numpy as np
from torchvision import datasets
if torch.cuda.is_available():
device = torch.device('cuda')
else:
device = torch.device('cpu')
class SIGCIFAR10(datasets.CIFAR10):
def __init__(self, root, train=True, transform=None, target_transform=None,
download=False, ... | 1,753 | 38.863636 | 101 | py |
CognitiveDistillation | CognitiveDistillation-main/datasets/celeba.py | from torchvision import datasets
class CustomCelebA(datasets.CelebA):
def __init__(self, root='/data/projects/punim0784/datasets',
split="train", target_type='attr', transform=None,
target_transform=None, download=False, **kwargs):
super().__init__(root=root, split=split,... | 1,653 | 49.121212 | 80 | py |
CognitiveDistillation | CognitiveDistillation-main/datasets/cifar_smooth.py | import torch
import numpy as np
from torchvision import datasets
if torch.cuda.is_available():
device = torch.device('cuda')
else:
device = torch.device('cpu')
def normalization(data):
_range = np.max(data) - np.min(data)
return (data - np.min(data)) / _range
class SmoothCIFAR10(datasets.CIFAR10):
... | 1,667 | 34.489362 | 101 | py |
CognitiveDistillation | CognitiveDistillation-main/datasets/issba.py | import torch
import numpy as np
from torchvision import datasets
from glob import glob
if torch.cuda.is_available():
device = torch.device('cuda')
else:
device = torch.device('cpu')
class ISSBAImageNetClean(datasets.folder.ImageFolder):
def __init__(self, root, transform=None, mode=None, **kwargs):
... | 1,848 | 36.734694 | 72 | py |
CognitiveDistillation | CognitiveDistillation-main/analysis/frequency.py | import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
from tqdm import tqdm
from scipy.fftpack import dct
if torch.cuda.is_available():
device = torch.device('cuda')
else:
device = torch.device('cpu')
class ConvBrunch(nn.Module):
def __init__(self, in_planes, out_planes, ke... | 3,690 | 29.254098 | 121 | py |
CognitiveDistillation | CognitiveDistillation-main/analysis/spectral_signatures.py | import numpy as np
import torch
from pyod.models.mad import MAD
def min_max_normalization(x):
x_min = torch.min(x)
x_max = torch.max(x)
norm = (x - x_min) / (x_max - x_min)
return norm
def get_ss_score(full_cov):
"""
https://github.com/MadryLab/backdoor_data_poisoning/blob/master/compute_cor... | 3,135 | 30.049505 | 89 | py |
CognitiveDistillation | CognitiveDistillation-main/analysis/cognitive_distillation.py | import torch
def min_max_normalization(x):
x_min = torch.min(x)
x_max = torch.max(x)
norm = (x - x_min) / (x_max - x_min)
return norm
class CognitiveDistillationAnalysis():
def __init__(self, od_type='l1_norm', norm_only=False):
self.od_type = od_type
self.norm_only = norm_only
... | 1,359 | 29.222222 | 99 | py |
CognitiveDistillation | CognitiveDistillation-main/analysis/activation_clustering.py | import numpy as np
from sklearn.cluster import KMeans
from sklearn.metrics import silhouette_samples
class ACAnalysis():
def __init__(self):
# Based on https://github.com/JonasGeiping/data-poisoning/blob/main/forest/filtering_defenses.py
return
def train(self, data, targets, cls_idx, clusters... | 2,839 | 34.5 | 104 | py |
CognitiveDistillation | CognitiveDistillation-main/analysis/abl.py | import torch
def min_max_normalization(x):
x_min = torch.min(x)
x_max = torch.max(x)
norm = (x - x_min) / (x_max - x_min)
return norm
class ABLAnalysis():
def __init__(self):
return
def analysis(self, data):
"""
data np.array
sample-wise training loss... | 541 | 22.565217 | 89 | py |
CognitiveDistillation | CognitiveDistillation-main/detection/get_features.py | import torch
import torch.nn as nn
class Feature_Detection(nn.Module):
def __init__(self):
super(Feature_Detection, self).__init__()
# Feature extraction for detections
def forward(self, model, images, labels):
if isinstance(model, torch.nn.DataParallel):
model.module.get_... | 706 | 29.73913 | 71 | py |
CognitiveDistillation | CognitiveDistillation-main/detection/strip.py | import torch
import torch.nn as nn
import numpy as np
import torch.nn.functional as F
class STRIP_Detection(nn.Module):
def __init__(self, data, alpha=1.0, beta=1.0, n=100):
super(STRIP_Detection, self).__init__()
self.data = data
self.alpha = alpha
self.beta = beta
self.n ... | 1,212 | 31.783784 | 67 | py |
CognitiveDistillation | CognitiveDistillation-main/detection/fct.py | import torch
import torch.nn as nn
import torch.nn.functional as F
import torchvision.transforms as transforms
from tqdm import tqdm
if torch.cuda.is_available():
torch.backends.cudnn.enabled = True
torch.backends.cudnn.benchmark = True
device = torch.device('cuda')
else:
device = torch.device('cpu')
... | 4,171 | 36.927273 | 102 | py |
CognitiveDistillation | CognitiveDistillation-main/detection/cognitive_distillation.py | import torch
import torch.nn as nn
def total_variation_loss(img, weight=1):
b, c, h, w = img.size()
tv_h = torch.pow(img[:, :, 1:, :]-img[:, :, :-1, :], 2).sum(dim=[1, 2, 3])
tv_w = torch.pow(img[:, :, :, 1:]-img[:, :, :, :-1], 2).sum(dim=[1, 2, 3])
return weight*(tv_h+tv_w)/(c*h*w)
class CognitiveD... | 2,455 | 38.612903 | 106 | py |
CognitiveDistillation | CognitiveDistillation-main/losses/__init__.py | import mlconfig
import torch
mlconfig.register(torch.nn.CrossEntropyLoss)
| 75 | 14.2 | 44 | py |
PhysioMRI_GUI | PhysioMRI_GUI-master/seq/petra.py | """
Created on Thu June 2 2022
@author: J.M. Algarín, MRILab, i3M, CSIC, Valencia
@email: josalggui@i3m.upv.es
@Summary: rare sequence class
"""
import os
import sys
import time
import numpy as np
import experiment as ex
import matplotlib.pyplot as plt
import scipy
import scipy.signal as sig
import pdb
import torch
im... | 22,283 | 47.12959 | 189 | py |
WL-Kernel-DGL | WL-Kernel-DGL-master/wlkernel/weisfeiler_lehman.py | import numpy as np
import torch as th
import dgl
def _send_color(edges):
return {'color': edges.src['color']}
def _gen_create_multiset(num_nodes):
def _create_multiset(nodes):
end = nodes.mailbox['color'].shape[1]
multiset = th.zeros((nodes.batch_size(), num_nodes)) - 1
multiset[:, 0] = nodes.data['... | 4,747 | 31.29932 | 96 | py |
provable-robustness-max-linear-regions | provable-robustness-max-linear-regions-master/eval.py | import argparse
import time
from datetime import datetime
import numpy as np
import os
import scipy.io
import tensorflow as tf
import torch
import torch.utils.data as td
from cleverhans.model import CallableModelWrapper
import attacks as ae
import data
import kolter_wong.eval as eval
import kolter_wong.models
import ... | 11,675 | 42.730337 | 134 | py |
provable-robustness-max-linear-regions | provable-robustness-max-linear-regions-master/kolter_wong/utils.py | import argparse
import numpy as np
import os
import scipy.io
import torch
import torch.utils.data as td
import torchvision.datasets as datasets
import torchvision.transforms as transforms
from torch.autograd import Variable
from kolter_wong.convex_adversarial import epsilon_from_model
def data_loader(dataset, batc... | 8,975 | 43 | 124 | py |
provable-robustness-max-linear-regions | provable-robustness-max-linear-regions-master/kolter_wong/eval.py | import numpy as np
import torch
from torch.autograd import Variable
from kolter_wong.convex_adversarial import DualNetBounds
def eval_lb_db(p_norm, model, loader, n_batches, device, alpha_init=1.0, epsilon_init=0.01, niters=20, threshold=1e-4):
q_norm = {2: 'l2', np.inf: 'l1'}[p_norm]
pred_correct, lbs = []... | 2,448 | 31.653333 | 126 | py |
provable-robustness-max-linear-regions | provable-robustness-max-linear-regions-master/kolter_wong/custom_layers.py | import torch
import math
import torch.nn.functional as F
from torch import nn
from torch.nn.modules.utils import _pair
class Conv2dUntiedBias(nn.Module):
def __init__(self, height, width, in_channels, out_channels, kernel_size, stride=1, padding=0, dilation=1,
groups=1):
super().__init__(... | 1,701 | 36 | 113 | py |
provable-robustness-max-linear-regions | provable-robustness-max-linear-regions-master/kolter_wong/models.py | import numpy as np
import scipy.io
import torch
import torch.nn as nn
import math
import data
from kolter_wong.convex_adversarial import Dense, DenseSequential
from kolter_wong.custom_layers import Conv2dUntiedBias
def select_model(model_type, n_in, n_out):
h_in, w_in, c_in = (28, 28, 1) if n_in == 28*28*1 else... | 6,808 | 31.117925 | 95 | py |
provable-robustness-max-linear-regions | provable-robustness-max-linear-regions-master/kolter_wong/trainer.py | import time
import torch
import torch.nn as nn
import torch.optim as optim
from torch.autograd import Variable
from kolter_wong.attacks import _pgd
from kolter_wong.convex_adversarial import robust_loss, robust_loss_parallel, robust_loss_with_point_errors
DEBUG = False
def train_robust(loader, model, opt, epsilon,... | 20,489 | 35.98556 | 149 | py |
provable-robustness-max-linear-regions | provable-robustness-max-linear-regions-master/kolter_wong/attacks.py | import torch
import torch.nn as nn
import torch.optim as optim
from torch.autograd import Variable
class Flatten(nn.Module):
def forward(self, x):
return x.view(x.size(0), -1)
def mean(l):
return sum(l)/len(l)
def _fgs(model, X, y, epsilon):
opt = optim.Adam([X], lr=1e-3)
out = model(X)
... | 3,103 | 31.673684 | 119 | py |
provable-robustness-max-linear-regions | provable-robustness-max-linear-regions-master/kolter_wong/convex_adversarial/dual_network.py | import torch
import torch.nn as nn
import torch.optim as optim
from torch.autograd import Variable
from .utils import Dense, DenseSequential
from .dual_inputs import select_input
from .dual_layers import select_layer
import warnings
class DualNetwork(nn.Module):
def __init__(self, net, X, epsilon, q_norm,
... | 7,332 | 34.597087 | 120 | py |
provable-robustness-max-linear-regions | provable-robustness-max-linear-regions-master/kolter_wong/convex_adversarial/dual_layers.py | import torch
import torch.nn as nn
import torch.nn.functional as F
import kolter_wong.custom_layers as cl
from .dual import DualLayer
from .utils import full_bias, Dense
def select_layer(layer, dual_net, X, l1_proj, l1_type, in_f, out_f, zsi,
zl=None, zu=None):
if isinstance(layer, nn.Linear):
... | 14,389 | 28.731405 | 117 | py |
provable-robustness-max-linear-regions | provable-robustness-max-linear-regions-master/kolter_wong/convex_adversarial/dual_inputs.py | import torch
import torch.nn as nn
from .dual import DualObject
def select_input(X, epsilon, l1_proj, l1_type, bounded_input, q_norm):
if l1_proj is not None and l1_type=='median' and X[0].numel() > l1_proj:
if bounded_input:
return InfBallProjBounded(X,epsilon,l1_proj)
else:
... | 5,845 | 33.591716 | 94 | py |
provable-robustness-max-linear-regions | provable-robustness-max-linear-regions-master/kolter_wong/convex_adversarial/dual.py | import torch.nn as nn
from abc import ABCMeta, abstractmethod
class DualObject(nn.Module, metaclass=ABCMeta):
def __init__(self):
""" Initialize a dual layer by initializing the variables needed to
compute this layer's contribution to the upper and lower bounds.
In the paper, if this o... | 1,722 | 34.163265 | 80 | py |
provable-robustness-max-linear-regions | provable-robustness-max-linear-regions-master/kolter_wong/convex_adversarial/utils.py | import torch.nn as nn
###########################################
# Helper function to extract fully #
# shaped bias terms #
###########################################
def full_bias(l, n=None):
# expands the bias to the proper size. For convolutional layers, a full
# output dime... | 4,058 | 30.96063 | 108 | py |
Bridge-Attention | Bridge-Attention-main/main_EfficientNet.py | """
Evaluate on ImageNet. Note that at the moment, training is not implemented (I am working on it).
that being said, evaluation is working.
"""
import argparse
import os
import random
import shutil
import time
import warnings
import PIL
import torch
import torch.nn as nn
import torch.nn.parallel
import torch.backend... | 17,670 | 37.667396 | 96 | py |
Bridge-Attention | Bridge-Attention-main/main.py | # -*- coding: UTF-8 -*-
import argparse
import os
import random
import shutil
import time
import warnings
import math
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.utils.data
import torch.utils.data.dist... | 16,128 | 35.49095 | 122 | py |
Bridge-Attention | Bridge-Attention-main/utils.py | import math
import torch
import torch.nn as nn
class CosineAnnealingLR:
def __init__(self, optimizer, T_max, eta_min=0, warmup=None, warmup_iters=None):
self.warmup = warmup
self.warmup_iters = warmup_iters
self.optimizer = optimizer
self.T_max = T_max
self.eta_min = eta_mi... | 4,326 | 36.95614 | 116 | py |
Bridge-Attention | Bridge-Attention-main/models/BA_mobilenetv3.py | import torch.nn as nn
import math
from models.BA_module import BA_module_mobilenetv3
__all__ = ['BA_MobileNetV3', 'ba_mobilenetv3_large', 'ba_mobilenetv3_small']
def _make_divisible(v, divisor, min_value=None):
"""
This function is taken from the original tf repo.
It ensures that all layers have a channe... | 8,762 | 32.446565 | 126 | py |
Bridge-Attention | Bridge-Attention-main/models/BA_resnet_fca.py | import torch.nn as nn
from torch.hub import load_state_dict_from_url
#from torchvision.models import ResNet
from models.BA_module import BA_module_resnet
from models.DCT_extration import MultiSpectralAttentionLayer
import torch
def conv3x3(in_planes, out_planes, stride=1):
return nn.Conv2d(in_planes, out_planes, ... | 11,319 | 36.607973 | 123 | py |
Bridge-Attention | Bridge-Attention-main/models/BA_resnext.py | import torch.nn as nn
import torch
import math
from models.BA_module import BA_module_resnet
__all__ = ['ResNeXt', 'resnext18', 'resnext34', 'resnext50', 'resnext101',
'resnext152', 'ba_resnext18', 'ba_resnext34','ba_resnext50', 'ba_resnext101',
'ba_resnext152']
def conv3x3(in_planes, out_planes,... | 12,617 | 31.353846 | 107 | py |
Bridge-Attention | Bridge-Attention-main/models/BA_resnet.py | import torch.nn as nn
from torch.hub import load_state_dict_from_url
#from torchvision.models import ResNet
from models.BA_module import BA_module_resnet
import torch
def conv3x3(in_planes, out_planes, stride=1):
return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride, padding=1, bias=False)
def con... | 8,825 | 33.611765 | 106 | py |
Bridge-Attention | Bridge-Attention-main/models/se_module.py | from torch import nn
class SELayer(nn.Module):
def __init__(self, channel, reduction=16):
super(SELayer, self).__init__()
self.avg_pool = nn.AdaptiveAvgPool2d(1)
self.fc = nn.Sequential(
nn.Linear(channel, channel // reduction, bias=False),
nn.ReLU(inplace=True),
... | 590 | 28.55 | 65 | py |
Bridge-Attention | Bridge-Attention-main/models/DCT_extration.py | import math
import torch
import torch.nn as nn
def get_freq_indices(method):
assert method in ['top1','top2','top4','top8','top16','top32',
'bot1','bot2','bot4','bot8','bot16','bot32',
'low1','low2','low4','low8','low16','low32']
num_freq = int(method[3:])
if 'to... | 4,825 | 39.554622 | 152 | py |
Bridge-Attention | Bridge-Attention-main/models/utils.py | """utils.py - Helper functions for building the model and for loading model parameters.
These helper functions are built to mirror those in the official TensorFlow implementation.
"""
# Author: lukemelas (github username)
# Github repo: https://github.com/lukemelas/EfficientNet-PyTorch
# With adjustments and added ... | 24,957 | 39.450567 | 130 | py |
Bridge-Attention | Bridge-Attention-main/models/mobilenetv3.py | import torch.nn as nn
import math
__all__ = ['mobilenetv3_large', 'mobilenetv3_small']
def _make_divisible(v, divisor, min_value=None):
"""
This function is taken from the original tf repo.
It ensures that all layers have a channel number that is divisible by 8
It can be seen here:
https://githu... | 7,197 | 31.423423 | 126 | py |
Bridge-Attention | Bridge-Attention-main/models/BA_effcientnet.py | """model.py - Model and module class for EfficientNet.
They are built to mirror those in the official TensorFlow implementation.
"""
# Author: lukemelas (github username)
# Github repo: https://github.com/lukemelas/EfficientNet-PyTorch
# With adjustments and added comments by workingcoder (github username).
import... | 18,701 | 40.932735 | 111 | py |
Bridge-Attention | Bridge-Attention-main/models/BA_module.py | from torch import nn
import torch
from functools import reduce
import torch.nn.functional as F
import math
class h_sigmoid(nn.Module):
def __init__(self, inplace=True):
super(h_sigmoid, self).__init__()
self.relu = nn.ReLU6(inplace=inplace)
def forward(self, x):
return self.relu(x + 3)... | 4,476 | 33.705426 | 102 | py |
Bridge-Attention | Bridge-Attention-main/models/se_resnet.py | import torch.nn as nn
from torch.hub import load_state_dict_from_url
from models.se_module import SELayer
import torch
def conv3x3(in_planes, out_planes, stride=1):
return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride, padding=1, bias=False)
def conv1x1(in_planes, out_planes, stride=1):
"""1x... | 12,704 | 31.493606 | 114 | py |
label-uncertainty-ser | label-uncertainty-ser-main/distributions.py | import constants as c
import torch
import math
import os
class Gaussian(object):
def __init__(self, mu, rho):
super().__init__()
self.mu = mu
self.rho = rho
# print("Normal Gauss Prior -> , N1: (0, ", str(sigma1), "), N2: (0, ", str(sigma2), ")")
self.normal = torch.distribu... | 1,386 | 32.02381 | 100 | py |
label-uncertainty-ser | label-uncertainty-ser-main/constants.py | import torch
import math
# Prior P(w) constants
PRIOR_VAR = 1.0
PRIOR_DIST = "gauss"
# Posterior P(w|D) constnts
PI = 0.5
SIGMA_1 = torch.FloatTensor([math.exp(-0)])
SIGMA_2 = torch.FloatTensor([math.exp(-6)]) | 211 | 18.272727 | 43 | py |
label-uncertainty-ser | label-uncertainty-ser-main/unit_test.py | import torch
from loss import calcUncertaintyLoss
from model import UncertaintyModel
from utils import ModelVariant
# Sample Input sequence, Shape same as in RECOLA, AVEC'16 for the following constanst,
batch_size = 25
audio_samplerate = 16 #in kHZ
label_samplerate = 40 #in ms
feature_dim = audio_samplerate * label_s... | 2,564 | 43.224138 | 149 | py |
label-uncertainty-ser | label-uncertainty-ser-main/loss.py | from torch.distributions import Normal, studentT
import torch
from kl_divergence_loss import kl_dist_dist
from utils import ModelVariant
def CCC(data1, data2):
mean1 = torch.mean(data1)
mean2 = torch.mean(data2)
std1 = torch.std(data1)
std2 = torch.std(data2)
dm = mean1 - mean2
ccc = (
... | 5,163 | 52.791667 | 212 | py |
label-uncertainty-ser | label-uncertainty-ser-main/utils.py | from enum import Enum
import torch
from distributions import ScaleMixtureGaussian
import constants as c
# Posterior intialization
def get_posterior_mu_init_range():
range = (-.1, .1)
return range
def get_posterior_rho_init_range():
range = (-3, -2)
return range
# Prior intialization
def get_pri... | 666 | 22 | 63 | py |
label-uncertainty-ser | label-uncertainty-ser-main/model.py | import torch.nn as nn
import torch
from layers import ParalingExtractor, TemporalExtractor, BayesMLP
import utils
##### Number of Parameter = 1,643,110
class UncertaintyModel(nn.Module):
def __init__(self, nout=2, ninp_lstm=320, nhidden_lstm=256, nlstm=2, dropout=0.5, uncertainty_samples=30, bbb_nsegments=50):
... | 6,663 | 57.45614 | 147 | py |
label-uncertainty-ser | label-uncertainty-ser-main/layers.py |
import torch.nn as nn
import torch
import math
from distributions import ScaleMixtureGaussian, Gaussian
import torch.nn.functional as F
import constants as c
import utils
########################## End-to-End backbone model ##########################
############# Layers: ParalingExtractor + TemporalExtractor ... | 7,274 | 43.907407 | 125 | py |
label-uncertainty-ser | label-uncertainty-ser-main/kl_divergence_loss.py | from torch.distributions import Normal, kl, studentT
import torch
import math
# Note: KL Div is not symmetric. So choice of which distribution is given as 1st arg is important.
@kl.register_kl(studentT.StudentT, Normal)
def kl_tstud_normal(p, q):
# Calculating KL-divergence based of Information theory
# i.e. ... | 1,272 | 35.371429 | 104 | py |
label-uncertainty-ser | label-uncertainty-ser-main/mspconv_reader.py | from scipy.signal import butter,filtfilt
from torch import index_select, tensor
from scipy.io import wavfile
from enum import Enum
import pandas as pd
import numpy as np
import librosa
import fnmatch
import torch
import os
# Annotation Filtering constants
window_size = 0.5 #mins
default_num_annot = 6
# Dataset consta... | 13,109 | 41.290323 | 165 | py |
OrthCDforRNNs | OrthCDforRNNs-main/optimizers.py | # -*- coding: utf-8 -*-
"""
This file contains the implementation of the optimizers described in the paper "Coordinate descent on the orthogonal group for recurrent
neural network training".
@version: May 2021
"""
import torch
from torch import nn
import torch.nn.functional as F
from torch.optim.optimizer import Opti... | 6,803 | 41.525 | 174 | py |
OrthCDforRNNs | OrthCDforRNNs-main/run_copying_problem.py | # -*- coding: utf-8 -*-
"""
This is the final code, with correct seed, to replicate the experiments of our Neurips paper. This code heavily relies (possibly verbatim, mainly regarding
model architecture and problem setting) on implementations from the project the projects https://github.com/Lezcano/geotorch and https... | 8,928 | 36.204167 | 164 | py |
cinc-challenge2017 | cinc-challenge2017-master/deeplearn-approach/train_model.py | '''
This function function used for training and cross-validating model using. The database is not
included in this repo, please download the CinC Challenge database and truncate/pad data into a
NxM matrix array, being N the number of recordings and M the window accepted by the network (i.e.
30 seconds).
For more... | 15,717 | 36.513126 | 129 | py |
cinc-challenge2017 | cinc-challenge2017-master/deeplearn-approach/predict.py | '''
This function loads one random recording from CinC Challenge and use pre-trained model in predicting what it is using Residual Networks
For more information visit: https://github.com/fernandoandreotti/cinc-challenge2017
Referencing this work
Andreotti, F., Carr, O., Pimentel, M.A.F., Mahdi, A., & De Vos, M. ... | 3,999 | 35.697248 | 135 | py |
SPACH | SPACH-main/main.py | # Copyright (c) 2015-present, Facebook, Inc.
# All rights reserved.
import argparse
import datetime
import numpy as np
import time
import torch
import torch.backends.cudnn as cudnn
import json
import os
from pathlib import Path
from timm.data import Mixup
from timm.models import create_model
from timm.loss import Lab... | 22,524 | 46.321429 | 125 | py |
SPACH | SPACH-main/losses.py | # Copyright (c) 2015-present, Facebook, Inc.
# All rights reserved.
"""
Implements the knowledge distillation loss
"""
import torch
from torch.nn import functional as F
class DistillationLoss(torch.nn.Module):
"""
This module wraps a standard criterion and adds an extra knowledge distillation loss by
taki... | 2,771 | 41.646154 | 114 | py |
SPACH | SPACH-main/engine.py | # Copyright (c) 2015-present, Facebook, Inc.
# All rights reserved.
"""
Train and eval functions used in main.py
"""
import math
import sys
from typing import Iterable, Optional
import time
import logging
import torch
from timm.data import Mixup
from timm.utils import accuracy, ModelEma
from losses import Distillati... | 4,228 | 34.537815 | 104 | py |
SPACH | SPACH-main/utils.py | # Copyright (c) 2015-present, Facebook, Inc.
# All rights reserved.
"""
Misc functions, including distributed helpers.
Mostly copy-paste from torchvision references.
"""
import io
import os
import time
from collections import defaultdict, deque
import datetime
import logging
import torch
import torch.distributed as d... | 7,665 | 30.036437 | 130 | py |
SPACH | SPACH-main/datasets.py | # Copyright (c) 2015-present, Facebook, Inc.
# All rights reserved.
import os
import json
from torchvision import datasets, transforms
from torchvision.datasets.folder import ImageFolder, default_loader
from timm.data.constants import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD
from timm.data import create_transform
... | 1,911 | 30.866667 | 97 | py |
SPACH | SPACH-main/samplers.py | # Copyright (c) 2015-present, Facebook, Inc.
# All rights reserved.
import torch
import torch.distributed as dist
import math
class RASampler(torch.utils.data.Sampler):
"""Sampler that restricts data loading to a subset of the dataset for distributed,
with repeated augmentation.
It ensures that different ... | 2,292 | 37.216667 | 103 | py |
SPACH | SPACH-main/models/shiftvit.py | # Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
import torch
import torch.nn as nn
import torch.utils.checkpoint as checkpoint
from timm.models.layers import DropPath, to_2tuple, trunc_normal_
from functools import partial
class GroupNorm(nn.GroupNorm):
def __init__(self, num_channels, n... | 11,998 | 33.088068 | 100 | py |
SPACH | SPACH-main/models/smlp.py | # Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
import torch
from torch import nn
from einops.layers.torch import Rearrange
from timm.models.layers import DropPath
class FeedForward(nn.Module):
def __init__(self, dim, hidden_dim, dropout=0.):
super().__init__()
self.net = ... | 4,749 | 35.538462 | 146 | py |
SPACH | SPACH-main/models/spach/misc.py | # Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
from functools import partial
from torch import nn
from einops import rearrange
from timm.models.layers import to_2tuple
def check_upstream_shape(x, img_size=(224, 224)):
_, _, H, W = x.shape
assert H == img_size[0] and W == img_size[1... | 2,519 | 30.898734 | 115 | py |
SPACH | SPACH-main/models/spach/spach_ms.py | # Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
from functools import partial
from torch import nn
from einops.layers.torch import Reduce
from .spach import MixingBlock, _init_weights
from .layers import STEM_LAYER, SPATIAL_FUNC
from .misc import DownsampleConv, reshape2n
class SpachMS(nn.M... | 5,295 | 38.819549 | 136 | py |
SPACH | SPACH-main/models/spach/spach.py | # Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
from functools import partial
import torch
from torch import nn
from timm.models.layers import DropPath
from einops.layers.torch import Reduce
from .layers import DWConv, SPATIAL_FUNC, ChannelMLP, STEM_LAYER
from .misc import reshape2n
class M... | 6,983 | 36.347594 | 172 | py |
SPACH | SPACH-main/models/spach/layers/stem.py | from torch import nn
from timm.models.layers import to_2tuple
from ..misc import check_upstream_shape
class PatchEmbed(nn.Module):
"""1-conv patch embedding layer"""
def __init__(self, img_size=224, patch_size=16, in_chans=3, embed_dim=768, downstream=False):
super().__init__()
img_size = to... | 3,548 | 35.587629 | 124 | py |
SPACH | SPACH-main/models/spach/layers/channel_func.py | from torch import nn
class ChannelMLP(nn.Module):
"""Channel MLP"""
def __init__(self, in_features, hidden_features=None, out_features=None, act_layer=nn.GELU, drop=0., **kwargs):
super(ChannelMLP, self).__init__()
out_features = out_features or in_features
hidden_features = hidden_fea... | 1,032 | 31.28125 | 115 | py |
SPACH | SPACH-main/models/spach/layers/spatial_func.py | from torch import nn
from einops import rearrange
from ..misc import Reshape2HW, Reshape2N
class SpatialAttention(nn.Module):
"""Spatial Attention"""
def __init__(self, dim, num_heads, qkv_bias=False, qk_scale=None, attn_drop=0., proj_drop=0., **kwargs):
super(SpatialAttention, self).__init__()
... | 3,229 | 28.633028 | 115 | py |
gnns-and-local-assortativity | gnns-and-local-assortativity-main/build_multigraph.py | import argparse
import logging
import os
import pickle
import networkx as nx
import numpy as np
import torch
from torch_geometric.data import Data
from torch_geometric.utils import to_networkx
from struc_sim import graph
from struc_sim import struc2vec
def parse_args():
parser = argparse.ArgumentParser()
parser.... | 5,766 | 29.675532 | 115 | py |
gnns-and-local-assortativity | gnns-and-local-assortativity-main/exp.py | import argparse
import copy
import logging
import math
import time
from pathlib import Path
import numpy as np
import torch
from tqdm import tqdm
from gnnutils import make_masks, train, test, add_original_graph, load_webkb, load_planetoid, load_wiki, load_bgp, \
load_film, structure_edge_weight_threshold
from models... | 5,863 | 33.292398 | 117 | py |
gnns-and-local-assortativity | gnns-and-local-assortativity-main/gnnutils.py | import copy
import networkx as nx
import numpy as np
import scipy.sparse as sparse
import torch
import torch.nn.functional as F
from networkx.utils import dict_to_numpy_array
from sklearn.metrics import f1_score
from sklearn.model_selection import train_test_split
from torch_geometric.datasets import Planetoid
from to... | 11,294 | 28.490862 | 112 | py |
gnns-and-local-assortativity | gnns-and-local-assortativity-main/models.py | import torch
import torch.nn.functional as F
from torch.nn import Sequential, Linear, ReLU
from torch_geometric.nn import GCNConv, GINConv, SAGEConv
from wrgat import WeightedRGATConv, GATConv
from wrgcn import WeightedRGCNConv
class WRGAT(torch.nn.Module):
def __init__(self, num_features, num_classes, num_relation... | 3,975 | 33.275862 | 114 | py |
gnns-and-local-assortativity | gnns-and-local-assortativity-main/wrgat.py | from typing import Union, Tuple, Optional
import torch
import torch.nn.functional as F
from torch import Tensor
from torch.nn import Parameter, Linear
from torch.nn import Parameter as Param
from torch_geometric.nn.conv import MessagePassing
from torch_geometric.nn.inits import glorot, zeros
from torch_geometric.typin... | 9,872 | 31.370492 | 135 | py |
gnns-and-local-assortativity | gnns-and-local-assortativity-main/wrgcn.py | from typing import Optional, Union, Tuple
import torch
from torch import Tensor
from torch.nn import Parameter
from torch.nn import Parameter as Param
from torch_geometric.nn.conv import MessagePassing
from torch_geometric.nn.inits import glorot, zeros
from torch_geometric.typing import OptTensor, Adj
from torch_spars... | 5,349 | 32.229814 | 99 | py |
gnns-and-local-assortativity | gnns-and-local-assortativity-main/datasets/wiki.py | import os.path as osp
import numpy as np
import torch
from torch_geometric.data import InMemoryDataset, download_url, Data
from torch_geometric.utils import to_undirected
from torch_sparse import coalesce
class WikipediaNetwork(InMemoryDataset):
url = 'https://raw.githubusercontent.com/graphdml-uiuc-jlu/geom-gc... | 2,959 | 36 | 79 | py |
gnns-and-local-assortativity | gnns-and-local-assortativity-main/datasets/bgp.py | import json
import shutil
import networkx as nx
import numpy as np
import torch
from torch_geometric.data import InMemoryDataset
from torch_geometric.utils import *
def convert_ndarray(x):
y = list(range(len(x)))
for k, v in x.items():
y[int(k)] = v
return np.array(y)
def check_rm(neighbors_set, unlabeled_nod... | 3,244 | 30.813725 | 92 | py |
gnns-and-local-assortativity | gnns-and-local-assortativity-main/datasets/film.py | import os.path as osp
import numpy as np
import torch
from torch_geometric.data import InMemoryDataset, download_url, Data
from torch_geometric.utils import to_undirected
from torch_sparse import coalesce
class FilmNetwork(InMemoryDataset):
url = 'https://raw.githubusercontent.com/graphdml-uiuc-jlu/geom-gcn/mas... | 3,073 | 34.333333 | 79 | py |
gnns-and-local-assortativity | gnns-and-local-assortativity-main/datasets/airports.py | import shutil
import networkx as nx
import numpy as np
import torch
from torch_geometric.data import InMemoryDataset
from torch_geometric.utils import *
def get_degrees(G):
num_nodes = G.number_of_nodes()
return np.array([G.degree[i] for i in range(num_nodes)])
class Airports(InMemoryDataset):
def __init__(self... | 2,223 | 27.151899 | 94 | py |
gnns-and-local-assortativity | gnns-and-local-assortativity-main/datasets/webkb.py | import os.path as osp
import numpy as np
import torch
from torch_geometric.data import InMemoryDataset, download_url, Data
from torch_geometric.utils import to_undirected
from torch_sparse import coalesce
class WebKB(InMemoryDataset):
url = 'https://raw.githubusercontent.com/graphdml-uiuc-jlu/geom-gcn/master'
... | 2,943 | 36.74359 | 79 | py |
gnns-and-local-assortativity | gnns-and-local-assortativity-main/struc_sim/graph.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Graph utilities."""
from collections import defaultdict, Iterable
from io import open
from itertools import permutations
from time import time
from six import iterkeys
from six.moves import range, zip_longest
from torch_geometric.utils import is_undirected, to_network... | 4,316 | 18.802752 | 102 | py |
RaPP | RaPP-main/src/train.py | import argparse
import torch
import pytorch_lightning as pl
from pytorch_lightning.loggers import MLFlowLogger
from rapp.data import MNISTDataModule
from rapp.models import (
AutoEncoder,
AdversarialAutoEncoder,
VariationalAutoEncoder,
RaPP,
)
def main(
model: str,
dataset: str,
target_l... | 4,252 | 31.465649 | 88 | py |
RaPP | RaPP-main/src/rapp/layer.py | import torch
import torch.nn as nn
class FullyConnectedLayer(nn.Module):
def __init__(self, input_size: int, output_size: int, act: str):
super().__init__()
layer = [nn.Linear(input_size, output_size), nn.BatchNorm1d(output_size)]
if act == "leakyrelu":
layer += [nn.LeakyReLU()... | 518 | 29.529412 | 81 | py |
RaPP | RaPP-main/src/rapp/models/adversarial_autoencoder.py | from typing import Tuple
import torch
import torch.nn as nn
from .autoencoder import AutoEncoder
from ..layer import FullyConnectedLayer
from ..utils import get_hidden_sizes
class AdversarialAutoEncoder(AutoEncoder):
def __init__(
self,
input_size: int,
hidden_size: int,
n_layers... | 3,812 | 30.775 | 85 | py |
RaPP | RaPP-main/src/rapp/models/autoencoder.py | from typing import Tuple
import torch
import torch.nn as nn
import pytorch_lightning as pl
from ..layer import FullyConnectedLayer
from ..utils import get_hidden_sizes
class AutoEncoder(pl.LightningModule):
def __init__(self, input_size: int, hidden_size: int, n_layers: int, loss_reduction: str= "sum"):
... | 2,130 | 34.516667 | 101 | py |
RaPP | RaPP-main/src/rapp/models/rapp.py | from typing import Any, Dict, List, Tuple
import torch
from torch.utils.data import DataLoader
from ..metrics import get_auroc, get_aupr
class RaPP:
def __init__(
self,
model,
rapp_start_index: int = 1,
rapp_end_index: int = -1,
loss_reduction: str = "sum",
):
... | 3,708 | 32.116071 | 86 | py |
RaPP | RaPP-main/src/rapp/models/variational_autoencoder.py | from logging import log
from typing import Tuple
import torch
import torch.nn as nn
from .autoencoder import AutoEncoder
from ..layer import FullyConnectedLayer
from ..utils import get_hidden_sizes
class VariationalAutoEncoder(AutoEncoder):
def __init__(
self,
input_size: int,
hidden_siz... | 3,379 | 31.190476 | 86 | py |
RaPP | RaPP-main/src/rapp/data/dataset.py | import torch
from torch.utils.data import Dataset
def _flatten(x):
return x.flatten()
def _normalize(x):
return x / 255
class CustomDataset(Dataset):
def __init__(self, data: torch.Tensor, label: torch.Tensor, transform: callable):
super().__init__()
assert data.size(0) == label.size(0... | 602 | 22.192308 | 85 | py |
RaPP | RaPP-main/src/rapp/data/mnist.py | from typing import Optional
import numpy as np
import torch
from torch.utils.data import DataLoader, random_split, ConcatDataset
from torchvision.datasets import MNIST
from torchvision import transforms as T
import pytorch_lightning as pl
from .dataset import CustomDataset, _flatten, _normalize
class MNISTDataModul... | 4,636 | 32.121429 | 85 | py |
CIM | CIM-main/test.py | import torch
import functools
from absl import flags
from absl import app
from oatomobile.benchmarks.carnovel.benchmark import carnovel
from oatomobile.baselines.torch.cim.model import ImitativeModel
from oatomobile.baselines.torch.cim.agent import CIMAgent
from oatomobile.baselines.torch.cim.predictor.model import MLP... | 1,907 | 25.873239 | 134 | py |
CIM | CIM-main/oatomobile/baselines/torch/traverse.py | """model.py"""
import numpy as np
import scipy
import math
import numbers
from PIL import Image
import torch
import imageio
def latent_traversal_1d_multi_dim(model,
latent_vector,
device,
dimensions=None,
... | 9,354 | 38.639831 | 84 | py |
CIM | CIM-main/oatomobile/baselines/torch/typing.py | # Copyright 2020 The OATomobile Authors. 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 at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | 886 | 34.48 | 80 | py |
CIM | CIM-main/oatomobile/baselines/torch/logging.py | # Copyright 2020 The OATomobile Authors. 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 at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | 5,321 | 28.731844 | 98 | py |
CIM | CIM-main/oatomobile/baselines/torch/models.py | # Copyright 2020 The OATomobile Authors. 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 at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | 3,436 | 31.424528 | 80 | py |
CIM | CIM-main/oatomobile/baselines/torch/__init__.py | # Copyright 2020 The OATomobile Authors. 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 at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | 1,045 | 46.545455 | 80 | py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.