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 |
|---|---|---|---|---|---|---|
transferlearning | transferlearning-master/code/utils/grl.py | '''
Gradient reversal layer. Reference:
Ganin et al. Unsupervised domain adaptation by backpropagation. ICML 2015.
'''
import torch
import numpy as np
# For pytorch version > 1.0
# Usage:
# b = GradReverse.apply(a, 1) # 1 is the lambda value, you are free to set it
class GradReverse(torch.autograd.Function):
@st... | 947 | 24.621622 | 80 | py |
DeepShallowParsingQA | DeepShallowParsingQA-master/common/word_vectorizer/glove.py | from common.word_vectorizer.wordVectorizer import WordVectorizer
from common.vocab import Vocab
import torch
import os
class Glove(WordVectorizer):
def __init__(self, dataset_vocab, glove_path, emb_path):
super(Glove, self).__init__(dataset_vocab)
if os.path.isfile(emb_path):
self.emb ... | 3,056 | 40.310811 | 109 | py |
DeepShallowParsingQA | DeepShallowParsingQA-master/common/dataset/base_dataset.py | from common.word_vectorizer.glove import Glove
from common.vocab import Vocab
from config import config
import torch
import torch.nn as nn
import os
import pickle as pk
import re
class Base_Dataset:
def __init__(self, trainset_path, testset_path, vocab_path, dataset_name='', remove_entity_mention=False,
... | 5,637 | 40.153285 | 119 | py |
DeepShallowParsingQA | DeepShallowParsingQA-master/common/model/environment.py | import torch
import logging
from common.utils import *
from config import config
from common.dataset.container.uri import URI
class Environment:
def __init__(self, entity_linker, relation_linker, positive_reward=1, negative_reward=-0.5, dataset=None, b=1):
self.positive_reward = positive_reward
se... | 18,433 | 51.518519 | 134 | py |
DeepShallowParsingQA | DeepShallowParsingQA-master/common/model/lstmPolicy.py | import torch
import torch.nn as nn
class LSTMPolicy(nn.Module):
def __init__(self, vocab_size, emb_size, input_size, hidden_size, output_size, dropout_ratio, emb_idx,
bidirectional=False):
super(LSTMPolicy, self).__init__()
self.output_size = output_size
self.emb_idx = emb... | 1,378 | 36.27027 | 106 | py |
DeepShallowParsingQA | DeepShallowParsingQA-master/common/model/policySplit.py | import torch
import torch.nn as nn
class PolicySplit(nn.Module):
def __init__(self, vocab_size, emb_size, input_size, hidden_size, output_size, dropout_ratio):
super(PolicySplit, self).__init__()
self.output_size = output_size
bias = True
self.emb = nn.Embedding(vocab_size, emb_si... | 1,217 | 35.909091 | 98 | py |
DeepShallowParsingQA | DeepShallowParsingQA-master/common/model/policy.py | import torch
import torch.nn as nn
class Policy(nn.Module):
def __init__(self, vocab_size, emb_size, input_size, hidden_size, output_size, dropout_ratio, emb_idx):
super(Policy, self).__init__()
self.output_size = output_size
self.emb_idx = emb_idx
bias = True
self.emb = n... | 1,308 | 34.378378 | 107 | py |
DeepShallowParsingQA | DeepShallowParsingQA-master/common/model/runner.py | import torch
import numpy as np
from tqdm import tqdm
import similarity.levenshtein
import similarity.ngram
import jellyfish
import logging
import os
from config import config
from common.model.agent import Agent
from common.model.policy import Policy
from common.model.lstmPolicy import LSTMPolicy
from common.model.po... | 16,759 | 51.704403 | 118 | py |
DeepShallowParsingQA | DeepShallowParsingQA-master/common/model/agent.py | import torch
import numpy as np
from common.utils import *
class Agent:
def __init__(self, number_of_relations, gamma, policy_network, split_network, policy_optimizer, split_optimizer,
no_split=True):
self.gamma = gamma
self.actions = range(number_of_relations + 1)
self.po... | 3,414 | 36.527473 | 116 | py |
DeepShallowParsingQA | DeepShallowParsingQA-master/common/linkers/candidate_generator/elasticCG.py | from config import config
import pickle as pk
import torch
class ElasticCG:
def __init__(self, elastic, index_name):
self.elastic = elastic
self.index_name = index_name
if 'relation' in self.index_name:
with open(config['dbpedia']['relations'] + '.coded', 'rb') as file_handler... | 995 | 30.125 | 87 | py |
DeepShallowParsingQA | DeepShallowParsingQA-master/common/linkers/candidate_generator/graphCG.py | import torch
import pickle as pk
import ujson as json
from common.utils import *
class GraphCG:
def __init__(self, rel2id_path, core_chains_path, dataset):
self.dataset = dataset
with open(rel2id_path, 'rb') as f_h:
self.rel2id = pk.load(f_h, encoding='latin1')
self.id2rel ... | 1,814 | 41.209302 | 116 | py |
DeepShallowParsingQA | DeepShallowParsingQA-master/common/linkers/sorter/embeddingSimilaritySorter.py | import numpy as np
import torch
import torch.nn as nn
from common.utils import *
class EmbeddingSimilaritySorter:
def __init__(self, word_vectorizer, threshold=0.4):
self.word_vectorizer = word_vectorizer
emb_shape = self.word_vectorizer.emb.shape
self.emb = nn.Embedding(emb_shape[0], emb_... | 2,347 | 45.039216 | 112 | py |
DeepShallowParsingQA | DeepShallowParsingQA-master/scripts/eval_mrr.py | import numpy as np
import torch
import logging
import time
import os
import ujson as json
from config import config
from scripts.config_args import parse_args
from common.dataset.lc_quad import LC_QuAD
from common.dataset.qald_7_ml import Qald_7_ml
from common.model.runner import Runner
np.random.seed(6)
torch.manual... | 1,911 | 33.142857 | 116 | py |
DeepShallowParsingQA | DeepShallowParsingQA-master/scripts/execute.py | import numpy as np
import torch
import logging
import time
from config import config
from scripts.config_args import parse_args
from common.dataset.lc_quad import LC_QuAD
from common.dataset.qald_7_ml import Qald_7_ml
from common.dataset.qald_6_ml import Qald_6_ml
from common.dataset.simple_dbpedia_qa import SimpleDBp... | 1,977 | 35.62963 | 116 | py |
DeepShallowParsingQA | DeepShallowParsingQA-master/scripts/eval.py | import numpy as np
import torch
import logging
import time
import os
import ujson as json
from config import config
from scripts.config_args import parse_args
from common.dataset.lc_quad import LC_QuAD
from common.dataset.qald_7_ml import Qald_7_ml
from common.model.runner import Runner
np.random.seed(6)
torch.manual... | 2,406 | 35.469697 | 116 | py |
DeepShallowParsingQA | DeepShallowParsingQA-master/scripts/create_vocab.py | import re
import os
from tqdm import tqdm
import ujson as json
import pickle as pk
import torch
from common.dataset.container.uri import URI
from config import config
from common.vocab import Vocab
from common.word_vectorizer.glove import Glove
from common.dataset.lc_quad import LC_QuAD
from common.dataset.qald_7_ml i... | 4,132 | 43.44086 | 114 | py |
DeepShallowParsingQA | DeepShallowParsingQA-master/scripts/baselines/lstm/lstm_annotated.py | import os
import ujson as json
import numpy as np
import torch
from scripts.baselines.lstm.lstm import *
from config import config
from common.dataset.lc_quad import LC_QuAD
from common.linkers.candidate_generator.datasetCG import DatasetCG
from common.linkers.sorter.stringSimilaritySorter import StringSimilaritySorte... | 4,968 | 45.009259 | 110 | py |
DeepShallowParsingQA | DeepShallowParsingQA-master/scripts/baselines/lstm/lstm.py | import jellyfish
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
import numpy as np
from nltk.corpus import stopwords
from tqdm import tqdm
import os
import similarity.ngram
from config import config
from common.dataset.lc_quad import LC_QuAD
from common.dataset.qald_6_ml... | 10,029 | 42.608696 | 128 | py |
DeepShallowParsingQA | DeepShallowParsingQA-master/scripts/dataset_prepration/entity_one_hop.py | import argparse
import re
import torch
import os
import pickle as pk
from tqdm import tqdm
from config import config
from common.dataset.lc_quad import LC_QuAD
from common.dataset.qald_7_ml import Qald_7_ml
from common.dataset.qald_6_ml import Qald_6_ml
from common.dataset.simple_dbpedia_qa import SimpleDBpediaQA
from ... | 3,307 | 41.410256 | 116 | py |
TraceCodegen | TraceCodegen-main/trainer.py | from pytorch_lightning import LightningModule, LightningDataModule
from pytorch_lightning.utilities.cli import LightningCLI
# see https://github.com/PyTorchLightning/pytorch-lightning/issues/10349
import warnings
warnings.filterwarnings(
"ignore", ".*Trying to infer the `batch_size` from an ambiguous collection.*... | 499 | 34.714286 | 81 | py |
TraceCodegen | TraceCodegen-main/lightning_modules/callbacks/save_prediction_callback.py | import os
import json
import torch
import pytorch_lightning as pl
from typing import Any, Dict, Optional, List
from pytorch_lightning.callbacks import Callback
from pathlib import Path
class SavePredictionCallback(Callback):
def __init__(self):
self.predictions = list()
self.prediction_save_dir = ... | 3,030 | 42.927536 | 122 | py |
TraceCodegen | TraceCodegen-main/lightning_modules/models/gpt_stmt_partial_mml_model.py | import torch
import time
import os
import json
import random
from itertools import chain
from concurrent.futures import ProcessPoolExecutor as Pool
from typing import Optional, Dict, Any, Tuple, List, Set, Union
from torch.nn import CrossEntropyLoss
from torchmetrics import MeanMetric
from pytorch_lightning import L... | 26,144 | 54.042105 | 152 | py |
TraceCodegen | TraceCodegen-main/lightning_modules/models/gpt_stmt_mml_model.py | import torch
import time
import os
import json
import random
from itertools import chain
from concurrent.futures import ProcessPoolExecutor as Pool
from typing import Optional, Dict, Any, Tuple, List, Set, Union
from torch.nn import CrossEntropyLoss
from torchmetrics import MeanMetric
from pytorch_lightning import L... | 15,446 | 55.170909 | 149 | py |
TraceCodegen | TraceCodegen-main/lightning_modules/models/gpt_seq2seq_model.py | import torch
import json
import os
import math
import torch.nn.functional as F
import pytorch_lightning as pl
import io, tokenize, re
import ast, astunparse
import numpy as np
from types import ModuleType
from typing import Optional, Dict, Any, Tuple, List
from transformers.optimization import AdamW, get_constant_sche... | 19,263 | 44.75772 | 136 | py |
TraceCodegen | TraceCodegen-main/lightning_modules/models/gpt_util.py | import torch
from typing import Tuple, Optional, List, Union
from transformers import GPTNeoForCausalLM, GPT2Tokenizer
from transformers import PreTrainedModel, PreTrainedTokenizer, GPT2LMHeadModel
from transformers import GPT2Tokenizer, GPTJForCausalLM
def get_gpt(model_name: str,
tokenizer_only: bool =... | 4,536 | 51.149425 | 143 | py |
TraceCodegen | TraceCodegen-main/lightning_modules/models/gpt_stmt_state_model.py | from numpy import dtype
import torch
import json
import os
import torch.nn.functional as F
import pytorch_lightning as pl
from typing import Optional, Dict, Any, Tuple, List
from transformers.optimization import AdamW, get_constant_schedule_with_warmup, get_linear_schedule_with_warmup
from torch.nn import CrossEntropy... | 12,479 | 54.466667 | 147 | py |
TraceCodegen | TraceCodegen-main/lightning_modules/loggers/patched_loggers.py | import os
import neptune
from typing import Optional, Union, List
from pytorch_lightning.loggers import NeptuneLogger, CSVLogger, TensorBoardLogger, WandbLogger
from pytorch_lightning.utilities import rank_zero_only
class PatchedWandbLogger(WandbLogger):
def __init__(self, entity: str, project: str, name: str, lo... | 3,288 | 38.626506 | 100 | py |
TraceCodegen | TraceCodegen-main/lightning_modules/datasets/mathqa_line_reader.py | import json
import logging
import sys
import os
from overrides import overrides
import torch
from typing import Dict, Iterable, List, Any, Optional, Union
from pytorch_lightning import LightningDataModule
from torch.utils.data import Dataset
from lightning_modules.models.gpt_util import get_gpt, left_pad_sequences
f... | 10,345 | 37.604478 | 117 | py |
LTNODE | LTNODE-main/LTNODE/test_LTNODE.py | import argparse
import os
import shutil
import time
import glob
import numpy as np
import torch
import torch.nn.parallel
import torch.utils.data
import torch.utils.data.distributed
from attacks.fgsm import FGSM
from attacks.pgd import PGD
from src.datasets.image_loaders import get_image_loader
from src.utils import ... | 17,907 | 38.884187 | 178 | py |
LTNODE | LTNODE-main/LTNODE/OOD_utils.py | import copy
import numpy as np
import torch
from torchvision import datasets, transforms
from sklearn.metrics import roc_curve, auc
from src.utils import DatafeedImage
def load_corrupted_dataset(dname, severity, data_dir='../../data', batch_size=256, cuda=True, workers=4):
assert dname in ['CIFAR10', 'CIFAR100'... | 10,769 | 35.508475 | 115 | py |
LTNODE | LTNODE-main/LTNODE/test_methods.py | import time
import torch
import torch.nn.functional as F
import numpy as np
from src.baselines.img_utils import load_img_resnet, img_resnet_predict
from src.baselines.img_utils import evaluate_predictive_entropy, ensemble_evaluate_predictive_entropy
from src.baselines.img_utils import get_preds_targets, ensemble_get_... | 18,001 | 43.669975 | 120 | py |
LTNODE | LTNODE-main/LTNODE/train_LTNODE.py | import argparse
import os
import shutil
import time
import glob
import numpy as np
import torch
import torch.nn.parallel
import torch.utils.data
import torch.utils.data.distributed
from src.datasets.image_loaders import get_image_loader
from src.utils import mkdir, save_object, cprint, load_object
from src.probabilit... | 9,610 | 35.267925 | 121 | py |
LTNODE | LTNODE-main/LTNODE/attacks/rfgsm.py | import torch
import torch.nn as nn
from ..attack import Attack
class RFGSM(Attack):
r"""
R+FGSM in the paper 'Ensemble Adversarial Training : Attacks and Defences'
[https://arxiv.org/abs/1705.07204]
Distance Measure : Linf
Arguments:
model (nn.Module): model to attack.
eps (... | 2,104 | 34.677966 | 161 | py |
LTNODE | LTNODE-main/LTNODE/attacks/apgdt.py | import time
import os
import sys
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from ..attack import Attack
class APGDT(Attack):
r"""
APGD-Targeted in the paper 'Reliable evaluation of adversarial robustness with an ensemble of diverse parameter-free attacks'
[htt... | 11,868 | 46.666667 | 195 | py |
LTNODE | LTNODE-main/LTNODE/attacks/tpgd.py | import torch
import torch.nn as nn
import torch.nn.functional as F
from ..attack import Attack
class TPGD(Attack):
r"""
PGD based on KL-Divergence loss in the paper 'Theoretically Principled Trade-off between Robustness and Accuracy'
[https://arxiv.org/abs/1901.08573]
Distance Measure : Linf
... | 2,197 | 33.34375 | 161 | py |
LTNODE | LTNODE-main/LTNODE/attacks/pgd.py | import torch
import torch.nn as nn
"""
PGD in the paper 'Towards Deep Learning Models Resistant to Adversarial Attacks'
[https://arxiv.org/abs/1706.06083]
Distance Measure : Linf
Arguments:
model (nn.Module): model to attack.
eps (float): maximum perturbation. (DEFAULT: 0.3)
... | 1,987 | 37.980392 | 161 | py |
LTNODE | LTNODE-main/LTNODE/attacks/autoattack.py | import time
import torch
import torch.nn as nn
import torch.nn.functional as F
from ..attack import Attack
from .multiattack import MultiAttack
from .apgd import APGD
from .apgdt import APGDT
from .fab import FAB
from .square import Square
class AutoAttack(Attack):
r"""
AutoAttack in the paper 'Reliable eva... | 4,107 | 45.157303 | 161 | py |
LTNODE | LTNODE-main/LTNODE/attacks/deepfool.py | import torch
import torch.nn as nn
from ..attack import Attack
class DeepFool(Attack):
r"""
'DeepFool: A Simple and Accurate Method to Fool Deep Neural Networks'
[https://arxiv.org/abs/1511.04599]
Distance Measure : L2
Arguments:
model (nn.Module): model to attack.
steps (in... | 3,967 | 34.428571 | 161 | py |
LTNODE | LTNODE-main/LTNODE/attacks/pgdl2.py | import torch
import torch.nn as nn
from ..attack import Attack
class PGDL2(Attack):
r"""
PGD in the paper 'Towards Deep Learning Models Resistant to Adversarial Attacks'
[https://arxiv.org/abs/1706.06083]
Distance Measure : L2
Arguments:
model (nn.Module): model to attack.
e... | 3,086 | 37.111111 | 161 | py |
LTNODE | LTNODE-main/LTNODE/attacks/vanila.py | import torch
import torch.nn as nn
from ..attack import Attack
class VANILA(Attack):
r"""
Vanila version of Attack.
It just returns the input images.
Arguments:
model (nn.Module): model to attack.
Shape:
- images: :math:`(N, C, H, W)` where `N = number of batches`, `C = numbe... | 993 | 27.4 | 161 | py |
LTNODE | LTNODE-main/LTNODE/attacks/sparsefool.py | import numpy as np
import torch
from ..attack import Attack
from .deepfool import DeepFool
class SparseFool(Attack):
r"""
Attack in the paper 'SparseFool: a few pixels make a big difference'
[https://arxiv.org/abs/1811.02248]
Modified from "https://github.com/LTS4/SparseFool/"
Distance... | 4,495 | 33.852713 | 161 | py |
LTNODE | LTNODE-main/LTNODE/attacks/cw.py | import torch
import torch.nn as nn
import torch.optim as optim
from ..attack import Attack
class CW(Attack):
r"""
CW in the paper 'Towards Evaluating the Robustness of Neural Networks'
[https://arxiv.org/abs/1608.04644]
Distance Measure : L2
Arguments:
model (nn.Module): model t... | 4,303 | 35.168067 | 161 | py |
LTNODE | LTNODE-main/LTNODE/attacks/gn.py | import torch
import torch.nn as nn
from ..attack import Attack
class GN(Attack):
r"""
Add Gaussian Noise.
Arguments:
model (nn.Module): model to attack.
sigma (nn.Module): sigma (DEFAULT: 0.1).
Shape:
- images: :math:`(N, C, H, W)` where `N = number of batches`, `C = numb... | 1,149 | 30.081081 | 161 | py |
LTNODE | LTNODE-main/LTNODE/attacks/_differential_evolution.py | """
Copied from "https://github.com/DebangLi/one-pixel-attack-pytorch/"
A slight modification to Scipy's implementation of differential evolution. To speed up predictions, the entire parameters array is passed to `self.func`, where a neural network model can batch its computations.
Taken from
https://github.com/scipy/... | 38,444 | 42.440678 | 210 | py |
LTNODE | LTNODE-main/LTNODE/attacks/fgsm.py | import torch
import torch.nn as nn
from torch.autograd import Variable
#from ..attack import Attack
"""
FGSM in the paper 'Explaining and harnessing adversarial examples'
[https://arxiv.org/abs/1412.6572]
Distance Measure : Linf
Arguments:
model (nn.Module): model to attack.
eps (f... | 1,569 | 36.380952 | 161 | py |
LTNODE | LTNODE-main/LTNODE/attacks/mifgsm.py | import torch
import torch.nn as nn
from ..attack import Attack
class MIFGSM(Attack):
r"""
MI-FGSM in the paper 'Boosting Adversarial Attacks with Momentum'
[https://arxiv.org/abs/1710.06081]
Distance Measure : Linf
Arguments:
model (nn.Module): model to attack.
eps (float): maxi... | 2,420 | 33.098592 | 161 | py |
LTNODE | LTNODE-main/LTNODE/attacks/apgd.py | import time
import os
import sys
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from ..attack import Attack
class APGD(Attack):
r"""
APGD in the paper 'Reliable evaluation of adversarial robustness with an ensemble of diverse parameter-free attacks'
[https://arxiv... | 12,484 | 45.585821 | 195 | py |
LTNODE | LTNODE-main/LTNODE/attacks/square.py | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import time
import os
import sys
import math
import torch
import torch.nn as nn
import torch.nn.functional as F
from ..attack import Attack
DEFAULT_EPS_DICT_BY_NORM = ... | 18,622 | 40.384444 | 192 | py |
LTNODE | LTNODE-main/LTNODE/attacks/multiattack.py | import torch
from ..attack import Attack
class MultiAttack(Attack):
r"""
MultiAttack is a class to attack a model with various attacks agains same images and labels.
Arguments:
model (nn.Module): model to attack.
attacks (list): list of attacks.
Examples::
>>> atta... | 2,002 | 30.793651 | 105 | py |
LTNODE | LTNODE-main/LTNODE/attacks/ffgsm.py | import torch
import torch.nn as nn
from ..attack import Attack
class FFGSM(Attack):
r"""
New FGSM proposed in 'Fast is better than free: Revisiting adversarial training'
[https://arxiv.org/abs/2001.03994]
Distance Measure : Linf
Arguments:
model (nn.Module): model to attack.
... | 2,016 | 33.775862 | 161 | py |
LTNODE | LTNODE-main/LTNODE/attacks/onepixel.py | import numpy as np
import torch
import torch.nn.functional as F
from ..attack import Attack
from ._differential_evolution import differential_evolution
class OnePixel(Attack):
r"""
Attack in the paper 'One pixel attack for fooling deep neural networks'
[https://arxiv.org/abs/1710.08864]
Modifie... | 4,862 | 39.190083 | 161 | py |
LTNODE | LTNODE-main/LTNODE/attacks/fab.py | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import time
import os
import sys
import math
import torch
from torch.autograd.gradcheck import zero_gradients
import torch.nn as nn
import torch.nn.functional as F
from... | 30,695 | 42.233803 | 194 | py |
LTNODE | LTNODE-main/LTNODE/attacks/bim.py | import torch
import torch.nn as nn
from ..attack import Attack
class BIM(Attack):
r"""
BIM or iterative-FGSM in the paper 'Adversarial Examples in the Physical World'
[https://arxiv.org/abs/1607.02533]
Distance Measure : Linf
Arguments:
model (nn.Module): model to attack.
ep... | 2,767 | 36.405405 | 161 | py |
LTNODE | LTNODE-main/LTNODE/attacks/pgddlr.py | import numpy as np
import torch
import torch.nn as nn
from ..attack import Attack
class PGDDLR(Attack):
r"""
PGD based on DLR loss in the paper 'Reliable evaluation of adversarial robustness with an ensemble of diverse parameter-free attacks'
[https://arxiv.org/abs/2003.01690]
[https://github.com/fr... | 2,965 | 37.025641 | 161 | py |
LTNODE | LTNODE-main/LTNODE/attacks/eotpgd.py | import torch
import torch.nn as nn
from ..attack import Attack
class EOTPGD(Attack):
r"""
Comment on "Adv-BNN: Improved Adversarial Defense through Robust Bayesian Neural Network"
[https://arxiv.org/abs/1907.00895]
Distance Measure : Linf
Arguments:
model (nn.Module): model to attac... | 2,441 | 33.394366 | 154 | py |
LTNODE | LTNODE-main/LTNODE/src/probability.py | import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.distributions import Normal
import numpy as np
from scipy.special import gamma
from torch.distributions.gamma import Gamma
from torch.distributions.uniform import Uniform
from src.utils import torch_onehot
#Line 202,105
def gumbel_softmax(l... | 14,156 | 37.786301 | 179 | py |
LTNODE | LTNODE-main/LTNODE/src/utils.py | import os
import sys
import pickle
import numpy as np
import torch
from torch.autograd import Variable
import torch.utils.data as data
import torch.nn.functional as F
from torch.distributions import Normal
from torch.optim.lr_scheduler import MultiStepLR
import torch.nn as nn
from PIL import Image
def mkdir(paths):
... | 7,310 | 27.897233 | 89 | py |
LTNODE | LTNODE-main/LTNODE/src/plots.py | import numpy as np
import torch
import torch.nn.functional as F
import matplotlib
import matplotlib.pyplot as plt
from src.utils import np_get_one_hot, generate_ind_batch, rms
matplotlib.use('Agg')
c = ['#1f77b4', '#ff7f0e', '#2ca02c', '#d62728', '#9467bd',
'#8c564b', '#e377c2', '#7f7f7f', '#bcbd22', '#17becf']... | 14,211 | 37 | 119 | py |
LTNODE | LTNODE-main/LTNODE/src/baselines/train_fc.py | import os
import time
import tempfile
import torch
import torch.utils.data
import numpy as np
from src.utils import mkdir, cprint
def train_fc_baseline(net, name, save_dir, batch_size, nb_epochs, trainloader, valloader, cuda, seed,
flat_ims=False, nb_its_dev=1, early_stop=None,
... | 4,426 | 33.858268 | 129 | py |
LTNODE | LTNODE-main/LTNODE/src/baselines/mfvi.py | import torch
import torch.nn.functional as F
import torch.nn as nn
from torch.autograd import Variable
def KLD_cost(mu_p, sig_p, mu_q, sig_q):
KLD = 0.5 * (2 * torch.log(sig_p / sig_q) - 1 + (sig_q / sig_p).pow(2) + ((mu_p - mu_q) / sig_p).pow(2)).sum()
# https://arxiv.org/abs/1312.6114 0.5 * sum(1 + log(sigm... | 4,990 | 36.526316 | 114 | py |
LTNODE | LTNODE-main/LTNODE/src/baselines/SGD.py | import random
import numpy as np
import torch
import torch.nn as nn
class res_MLPBlock(nn.Module):
"""Skippable MLPBlock with relu"""
def __init__(self, width):
super(res_MLPBlock, self).__init__()
self.block = nn.Sequential(nn.Linear(width, width), nn.ReLU(), nn.BatchNorm1d(width)) # nn.Laye... | 1,827 | 32.851852 | 165 | py |
LTNODE | LTNODE-main/LTNODE/src/baselines/img_utils.py | from collections import OrderedDict
import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
def load_img_resnet(model, savefile, gpu=None):
cuda_enabled = torch.cuda.is_available()
if cuda_enabled:
if gpu is None:
if not isinstance(model, nn.DataParallel):
... | 5,586 | 33.91875 | 111 | py |
LTNODE | LTNODE-main/LTNODE/src/baselines/dropout.py | import torch
import torch.nn.functional as F
import torch.nn as nn
class res_DropoutBlock(nn.Module):
"""Skippable MLPBlock with relu"""
def __init__(self, width, p_drop=0.5):
super(res_DropoutBlock, self).__init__()
self.p_drop = p_drop
self.block = nn.Sequential(nn.Linear(width, widt... | 2,312 | 33.014706 | 91 | py |
LTNODE | LTNODE-main/LTNODE/src/baselines/training_wrappers.py | import random
import numpy as np
import torch
import torch.backends.cudnn as cudnn
from src.utils import BaseNet, cprint, to_variable
from src.utils import rms
from src.probability import homo_Gauss_mloglike
def ensemble_predict(net, savefiles, x, return_model_std=False, return_individual_functions=False, to_cpu=F... | 6,024 | 37.870968 | 130 | py |
LTNODE | LTNODE-main/LTNODE/src/datasets/image_loaders.py | import os
from PIL import Image
import h5py
import torch
from torchvision import transforms, datasets
from torchvision.datasets import VisionDataset
def get_image_loader(dname, batch_size, cuda, workers, distributed, data_dir='../../data', subset=None):
assert dname in ['MNIST', 'Fashion', 'SVHN', 'CIFAR10', 'C... | 9,459 | 35.809339 | 110 | py |
LTNODE | LTNODE-main/LTNODE/src/DUN/train_fc.py | import os
import time
import tempfile
import numpy as np
import torch
import torch.utils.data
from src.utils import mkdir, cprint
def train_fc_DUN(net, name, save_dir, batch_size, nb_epochs, train_loader, val_loader,
cuda, seed, flat_ims=False, nb_its_dev=1, early_stop=None,
track_poster... | 5,435 | 34.529412 | 122 | py |
LTNODE | LTNODE-main/LTNODE/src/DUN/stochastic_fc_models.py | import torch
import torch.nn as nn
from src.DUN.layers import bern_MLPBlock, bern_MLPBlock_nores
class arq_uncert_fc_resnet(nn.Module):
def __init__(self, input_dim, output_dim, width, n_layers, w_prior=None, BMA_prior=False):
super(arq_uncert_fc_resnet, self).__init__()
self.input_dim = input_d... | 3,365 | 40.04878 | 112 | py |
LTNODE | LTNODE-main/LTNODE/src/DUN/stochastic_toy_node.py | import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.nn.modules.dropout import _DropoutNd
import torch.nn.init as init
__all__ = ['toy']
class ConcatConv2d(nn.Module):
def __init__(self, dim_in, dim_out, ksize=3, stride=1, padding=0, dilation=1, groups=1, bias=True, transpose=False):
... | 7,021 | 27.42915 | 120 | py |
LTNODE | LTNODE-main/LTNODE/src/DUN/layers.py | import torch.nn as nn
class global_mean_pool_2d(nn.Module):
def __init__(self):
super(global_mean_pool_2d, self).__init__()
def forward(self, x):
return x.mean(dim=(2, 3))
class res_MLPBlock(nn.Module):
def __init__(self, width):
super(res_MLPBlock, self).__init__()
self... | 6,037 | 33.112994 | 111 | py |
LTNODE | LTNODE-main/LTNODE/src/DUN/stochastic_toy_node (copy).py | import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.nn.modules.dropout import _DropoutNd
import torch.nn.init as init
__all__ = ['toy']
class ConcatConv2d(nn.Module):
def __init__(self, dim_in, dim_out, ksize=3, stride=1, padding=0, dilation=1, groups=1, bias=True, transpose=False):
... | 6,705 | 27.058577 | 120 | py |
LTNODE | LTNODE-main/LTNODE/src/DUN/sdenet_mnist.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Mar 11 16:42:11 2019
@author: lingkaikong
"""
import torch
import torch.nn as nn
import torch.nn.functional as F
import random
import torch.nn.init as init
import math
__all__ = ['SDENet_mnist']
def init_params(net):
'''Init layer parameters.'''
... | 5,255 | 30.473054 | 147 | py |
LTNODE | LTNODE-main/LTNODE/src/DUN/stochastic_concentric_node.py | import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.nn.modules.dropout import _DropoutNd
import torch.nn.init as init
__all__ = ['concentric']
class NODE(nn.Module):
def __init__(self, dim):
super(NODE, self).__init__()
#self.norm1 = norm(dim)
#self.tanh = nn... | 4,114 | 27.978873 | 77 | py |
LTNODE | LTNODE-main/LTNODE/src/DUN/training_wrappers.py | import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.backends.cudnn as cudnn
from src.utils import BaseNet, cprint, to_variable
from src.utils import rms
from src.probability import homo_Gauss_mloglike, depth_gamma
class DUN(BaseNet):
def __init__(self, model, prob_model, N_train, lr=1... | 15,870 | 48.442368 | 205 | py |
LTNODE | LTNODE-main/LTNODE/src/DUN/stochastic_img_resnets.py | import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.nn.modules.dropout import _DropoutNd
import torch.nn.init as init
__all__ = ['ResNet', 'resnet18', 'resnet34', 'resnet50', 'resnet101','simple','simple1']
class MC_Dropout2d(_DropoutNd):
def forward(self, input):
return F.drop... | 21,633 | 36.171821 | 282 | py |
LTNODE | LTNODE-main/LTNODE/src/DUN/sdode_img_resnets.py | import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.nn.modules.dropout import _DropoutNd
import torch.nn.init as init
__all__ = ['ResNet', 'resnet18', 'resnet34', 'resnet50', 'resnet101','simple']
class MC_Dropout2d(_DropoutNd):
def forward(self, input):
return F.dropout2d(inpu... | 17,750 | 35.98125 | 282 | py |
LTNODE | LTNODE-main/LTNODE/torch_ACA/misc.py | """
Misc functions forked from https://github.com/rtqichen/torchdiffeq/blob/master/torchdiffeq/_impl/misc.py
"""
import torch
import warnings
def _possibly_nonzero(x):
return isinstance(x, torch.Tensor) or x != 0
def _scaled_dot_product(scale, xs, ys):
"""Calculate a scaled, vector inner product between lists... | 3,325 | 38.595238 | 110 | py |
LTNODE | LTNODE-main/LTNODE/torch_ACA/fixed_grid_solver.py | import abc
import torch
import copy
import numpy as np
from torch import nn
from .utils import monotonic
__all__ = ['Euler','RK2','RK4']
class FixedGridSolver(nn.Module):
__metaclass__ = abc.ABCMeta
def __init__(self, func, t0=0.0, t1=1.0, h = 0.1, rtol=1e-3, atol=1e-6, neval_max=500000,
pri... | 9,753 | 36.953307 | 167 | py |
LTNODE | LTNODE-main/LTNODE/torch_ACA/odesolver/adaptive_grid_solver.py | """
This file contains a class of ODE solvers, which support arbitraty evaluation time between initial time t0, and end time t1.
e.g. evaluate at time points s1, s2, s3, s4, .. where t0 < s1 < s2 < ... t1
or t1 < s1 < s2 < s3 < ... t0
The freedom with evaluation time points comes at a price, that it's hard t... | 33,136 | 41.979248 | 135 | py |
LTNODE | LTNODE-main/LTNODE/torch_ACA/odesolver_mem/adaptive_grid_solver_endtime.py | """
This file contains a class of ODE solvers, which support "checkpoint" strategy to save memory.
However, denoting the initial time as t0 and end time as t1, this file only supports evaluate at t1.
t1 can be either greater or smaller than t0.
"""
import abc
import torch
import copy
import numpy as np
from torch.autog... | 25,077 | 40.657807 | 182 | py |
LTNODE | LTNODE-main/LTNODE/torch_ACA/odesolver_mem/adjoint_mem.py |
import torch
import torch.nn as nn
from .ode_solver_endtime import odesolve_endtime
from torch.autograd import Variable
import copy
__all__ = ['odesolve_adjoint']
def flatten_params(params):
flat_params = [p.contiguous().view(-1) for p in params]
return torch.cat(flat_params) if len(flat_params) > 0 else torc... | 6,639 | 33.947368 | 153 | py |
LTNODE | LTNODE-main/ALTNODE/test_ALTNODE.py | import argparse
import os
import shutil
import time
import glob
import numpy as np
import torch
import torch.nn.parallel
import torch.utils.data
import torch.utils.data.distributed
from attacks.fgsm import FGSM
from attacks.pgd import PGD
from src.datasets.image_loaders import get_image_loader
from src.utils import m... | 18,812 | 39.545259 | 178 | py |
LTNODE | LTNODE-main/ALTNODE/train_ALTNODE.py | import argparse
import os
import shutil
import time
import glob
import numpy as np
import torch
import torch.nn.parallel
import torch.utils.data
import torch.utils.data.distributed
import random
from src.datasets.image_loaders import get_image_loader
from src.utils import mkdir, save_object, cprint, load_object
from s... | 9,973 | 35.940741 | 121 | py |
LTNODE | LTNODE-main/ALTNODE/OOD_utils.py | import copy
import numpy as np
import torch
from torchvision import datasets, transforms
from sklearn.metrics import roc_curve, auc
from src.utils import DatafeedImage
def load_corrupted_dataset(dname, severity, data_dir='../../data', batch_size=256, cuda=True, workers=4):
assert dname in ['CIFAR10', 'CIFAR100'... | 10,421 | 35.826855 | 115 | py |
LTNODE | LTNODE-main/ALTNODE/test_methods.py | import time
import torch
import torch.nn.functional as F
import numpy as np
from src.baselines.img_utils import load_img_resnet, img_resnet_predict
from src.baselines.img_utils import evaluate_predictive_entropy, ensemble_evaluate_predictive_entropy
from src.baselines.img_utils import get_preds_targets, ensemble_get_... | 18,001 | 43.669975 | 120 | py |
LTNODE | LTNODE-main/ALTNODE/attacks/rfgsm.py | import torch
import torch.nn as nn
from ..attack import Attack
class RFGSM(Attack):
r"""
R+FGSM in the paper 'Ensemble Adversarial Training : Attacks and Defences'
[https://arxiv.org/abs/1705.07204]
Distance Measure : Linf
Arguments:
model (nn.Module): model to attack.
eps (... | 2,104 | 34.677966 | 161 | py |
LTNODE | LTNODE-main/ALTNODE/attacks/apgdt.py | import time
import os
import sys
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from ..attack import Attack
class APGDT(Attack):
r"""
APGD-Targeted in the paper 'Reliable evaluation of adversarial robustness with an ensemble of diverse parameter-free attacks'
[htt... | 11,868 | 46.666667 | 195 | py |
LTNODE | LTNODE-main/ALTNODE/attacks/tpgd.py | import torch
import torch.nn as nn
import torch.nn.functional as F
from ..attack import Attack
class TPGD(Attack):
r"""
PGD based on KL-Divergence loss in the paper 'Theoretically Principled Trade-off between Robustness and Accuracy'
[https://arxiv.org/abs/1901.08573]
Distance Measure : Linf
... | 2,197 | 33.34375 | 161 | py |
LTNODE | LTNODE-main/ALTNODE/attacks/pgd.py | import torch
import torch.nn as nn
"""
PGD in the paper 'Towards Deep Learning Models Resistant to Adversarial Attacks'
[https://arxiv.org/abs/1706.06083]
Distance Measure : Linf
Arguments:
model (nn.Module): model to attack.
eps (float): maximum perturbation. (DEFAULT: 0.3)
... | 2,138 | 39.358491 | 161 | py |
LTNODE | LTNODE-main/ALTNODE/attacks/autoattack.py | import time
import torch
import torch.nn as nn
import torch.nn.functional as F
from ..attack import Attack
from .multiattack import MultiAttack
from .apgd import APGD
from .apgdt import APGDT
from .fab import FAB
from .square import Square
class AutoAttack(Attack):
r"""
AutoAttack in the paper 'Reliable eva... | 4,107 | 45.157303 | 161 | py |
LTNODE | LTNODE-main/ALTNODE/attacks/deepfool.py | import torch
import torch.nn as nn
from ..attack import Attack
class DeepFool(Attack):
r"""
'DeepFool: A Simple and Accurate Method to Fool Deep Neural Networks'
[https://arxiv.org/abs/1511.04599]
Distance Measure : L2
Arguments:
model (nn.Module): model to attack.
steps (in... | 3,967 | 34.428571 | 161 | py |
LTNODE | LTNODE-main/ALTNODE/attacks/pgdl2.py | import torch
import torch.nn as nn
from ..attack import Attack
class PGDL2(Attack):
r"""
PGD in the paper 'Towards Deep Learning Models Resistant to Adversarial Attacks'
[https://arxiv.org/abs/1706.06083]
Distance Measure : L2
Arguments:
model (nn.Module): model to attack.
e... | 3,086 | 37.111111 | 161 | py |
LTNODE | LTNODE-main/ALTNODE/attacks/vanila.py | import torch
import torch.nn as nn
from ..attack import Attack
class VANILA(Attack):
r"""
Vanila version of Attack.
It just returns the input images.
Arguments:
model (nn.Module): model to attack.
Shape:
- images: :math:`(N, C, H, W)` where `N = number of batches`, `C = numbe... | 993 | 27.4 | 161 | py |
LTNODE | LTNODE-main/ALTNODE/attacks/sparsefool.py | import numpy as np
import torch
from ..attack import Attack
from .deepfool import DeepFool
class SparseFool(Attack):
r"""
Attack in the paper 'SparseFool: a few pixels make a big difference'
[https://arxiv.org/abs/1811.02248]
Modified from "https://github.com/LTS4/SparseFool/"
Distance... | 4,495 | 33.852713 | 161 | py |
LTNODE | LTNODE-main/ALTNODE/attacks/cw.py | import torch
import torch.nn as nn
import torch.optim as optim
from ..attack import Attack
class CW(Attack):
r"""
CW in the paper 'Towards Evaluating the Robustness of Neural Networks'
[https://arxiv.org/abs/1608.04644]
Distance Measure : L2
Arguments:
model (nn.Module): model t... | 4,303 | 35.168067 | 161 | py |
LTNODE | LTNODE-main/ALTNODE/attacks/gn.py | import torch
import torch.nn as nn
from ..attack import Attack
class GN(Attack):
r"""
Add Gaussian Noise.
Arguments:
model (nn.Module): model to attack.
sigma (nn.Module): sigma (DEFAULT: 0.1).
Shape:
- images: :math:`(N, C, H, W)` where `N = number of batches`, `C = numb... | 1,149 | 30.081081 | 161 | py |
LTNODE | LTNODE-main/ALTNODE/attacks/_differential_evolution.py | """
Copied from "https://github.com/DebangLi/one-pixel-attack-pytorch/"
A slight modification to Scipy's implementation of differential evolution. To speed up predictions, the entire parameters array is passed to `self.func`, where a neural network model can batch its computations.
Taken from
https://github.com/scipy/... | 38,444 | 42.440678 | 210 | py |
LTNODE | LTNODE-main/ALTNODE/attacks/fgsm.py | import torch
import torch.nn as nn
from torch.autograd import Variable
#from ..attack import Attack
"""
FGSM in the paper 'Explaining and harnessing adversarial examples'
[https://arxiv.org/abs/1412.6572]
Distance Measure : Linf
Arguments:
model (nn.Module): model to attack.
eps (f... | 2,456 | 35.132353 | 161 | py |
LTNODE | LTNODE-main/ALTNODE/attacks/mifgsm.py | import torch
import torch.nn as nn
from ..attack import Attack
class MIFGSM(Attack):
r"""
MI-FGSM in the paper 'Boosting Adversarial Attacks with Momentum'
[https://arxiv.org/abs/1710.06081]
Distance Measure : Linf
Arguments:
model (nn.Module): model to attack.
eps (float): maxi... | 2,420 | 33.098592 | 161 | py |
LTNODE | LTNODE-main/ALTNODE/attacks/apgd.py | import time
import os
import sys
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from ..attack import Attack
class APGD(Attack):
r"""
APGD in the paper 'Reliable evaluation of adversarial robustness with an ensemble of diverse parameter-free attacks'
[https://arxiv... | 12,484 | 45.585821 | 195 | py |
LTNODE | LTNODE-main/ALTNODE/attacks/square.py | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import time
import os
import sys
import math
import torch
import torch.nn as nn
import torch.nn.functional as F
from ..attack import Attack
DEFAULT_EPS_DICT_BY_NORM = ... | 18,622 | 40.384444 | 192 | py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.