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 |
|---|---|---|---|---|---|---|
CoCLR | CoCLR-main/utils/augmentation.py | import random
import numbers
import math
import collections
import torchvision
from torchvision import transforms
import torchvision.transforms.functional as F
from PIL import ImageOps, Image, ImageFilter
import numpy as np
from joblib import Parallel, delayed
class Padding:
def __init__(self, pad):
self.... | 17,588 | 37.071429 | 126 | py |
CoCLR | CoCLR-main/utils/utils.py | import os
import glob
import math
import pickle
import numpy as np
import torch
from torchvision import transforms
from datetime import datetime
from collections import deque
def save_checkpoint(state, is_best=0, gap=1, filename='models/checkpoint.pth.tar', keep_all=False):
torch.save(state, filename)
last_ep... | 8,791 | 32.815385 | 118 | py |
CoCLR | CoCLR-main/utils/transforms.py | # from references/video_classification
# and torchvision/transforms/functional_tensor.py
# Support data argumentation for 4D tensor, [N, H, W, C]
import torch
import random
import numbers
import torchvision
import numpy as np
import math
def crop(vid, i, j, h, w):
return vid[..., i:(i + h), j:(j + w)]
def cen... | 13,449 | 34.209424 | 123 | py |
CoCLR | CoCLR-main/model/pretrain.py | # MoCo-related code is modified from https://github.com/facebookresearch/moco
import sys
import math
import random
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
sys.path.append('../')
from backbone.select_backbone import select_backbone
# utils
@torch.no_grad()
def concat_all_g... | 14,821 | 34.374702 | 101 | py |
CoCLR | CoCLR-main/model/classifier.py | import sys
import math
import torch
import torch.nn as nn
import torch.nn.functional as F
sys.path.append('../')
from backbone.select_backbone import select_backbone
class LinearClassifier(nn.Module):
def __init__(self, num_class=101,
network='resnet50',
dropout=0.5,
... | 2,368 | 32.842857 | 85 | py |
refresh2018-predicting-trends-from-arxiv | refresh2018-predicting-trends-from-arxiv-master/encode_sentences.py | """Encodes textparts as InferSent embeddings
Attributes:
glovePath (str): path to glove embeddings
infersentpath (str): path to infersent.allnli.pickle
"""
import datahandler
from mydate import valid_date
import argparse
import torch
import os.path
import tensorflow_hub as hub
import tensorflow as tf
import ... | 5,310 | 36.401408 | 122 | py |
refresh2018-predicting-trends-from-arxiv | refresh2018-predicting-trends-from-arxiv-master/make_predictions.py | import argparse
from nltk.tokenize import word_tokenize
from pathlib import Path
from mydate import valid_date
from encode_sentences import infersent_encode_texts
from sklearn.externals import joblib
import datahandler
from train_models import vectorize
from keras.models import load_model
import numpy as np
parser = ... | 2,679 | 31.289157 | 95 | py |
refresh2018-predicting-trends-from-arxiv | refresh2018-predicting-trends-from-arxiv-master/train_models.py | import argparse
import numpy as np
from scipy.stats import pearsonr
from keras.callbacks import EarlyStopping, ModelCheckpoint
from keras.layers import Input, Dense, Dropout
from keras.models import Model
from keras.models import load_model
from sklearn import linear_model
from sklearn.externals import joblib
from sk... | 8,748 | 33.856574 | 211 | py |
SOAPify | SOAPify-main/docs/source/conf.py | # Configuration file for the Sphinx documentation builder.
#
# This file only contains a selection of the most common options. For a full
# list see the documentation:
# https://www.sphinx-doc.org/en/master/usage/configuration.html
# -- Path setup --------------------------------------------------------------
# If ex... | 3,345 | 30.866667 | 79 | py |
annotator-heuristics | annotator-heuristics-main/code/run_qa.py | #!/usr/bin/env python
# coding=utf-8
# Copyright The HuggingFace Team and The HuggingFace Inc. team. 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.ap... | 22,391 | 41.814532 | 219 | py |
PLMs-Interpret-Simile | PLMs-Interpret-Simile-main/code/distant_supervision/main.py | import torch
from torch import nn
from torch.utils.data import Dataset, DataLoader
from transformers import AutoTokenizer, AutoModel
from transformers import AdamW, get_scheduler
from tqdm import tqdm
from sklearn import model_selection,metrics
import random
import wandb
import os
import pdb
import argparse
import nump... | 7,732 | 35.305164 | 187 | py |
PLMs-Interpret-Simile | PLMs-Interpret-Simile-main/code/distant_supervision/dataloader.py |
import torch
import re
import pickle
from tqdm import tqdm
from copy import deepcopy
import torch.nn.functional as F
from torch.utils.data import Dataset, DataLoader
import random
class DatasetforSimile(Dataset):
def __init__(self, data, tokenizer, max_seq_len = 128, max_comp_len = 5):
super(DatasetforS... | 4,647 | 37.733333 | 154 | py |
PLMs-Interpret-Simile | PLMs-Interpret-Simile-main/code/distant_supervision/model.py | from transformers import AutoTokenizer, AutoModelForMaskedLM
from tqdm import tqdm
from sklearn import metrics
import transformers
import random
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.utils.data import Dataset, DataLoader
from torch.nn import CrossEntropyLoss, M... | 4,704 | 35.472868 | 172 | py |
PLMs-Interpret-Simile | PLMs-Interpret-Simile-main/code/zero-shot/cloze_bert.py | import torch
import pandas as pd
from transformers import BertTokenizer, BertModel, BertForMaskedLM
from tqdm import tqdm
import numpy as np
from sklearn import metrics
import random
import os
import argparse
import numpy as np
def set_random_seed(seed):
random.seed(seed)
os.environ['PYTHONHASHSEED'] = str(see... | 2,839 | 34.061728 | 97 | py |
PLMs-Interpret-Simile | PLMs-Interpret-Simile-main/code/zero-shot/cloze_roberta.py | import torch
import pandas as pd
from transformers import RobertaTokenizer, RobertaForMaskedLM
from tqdm import tqdm
import numpy as np
from sklearn import metrics
import random
import os
import pdb
import argparse
import numpy as np
def set_random_seed(seed):
random.seed(seed)
os.environ['PYTHONHASHSEED'] = s... | 2,913 | 34.536585 | 114 | py |
tafe-net | tafe-net-master/tafenet.py | import torch
import torch.nn as nn
import torch.nn.functional as F
import pdb
class TAFENet(nn.Module):
def __init__(self, meta_learner, config, feature_in_dim, feat_dim, **kwargs):
super(TAFENet, self).__init__()
self.config = config
self.cin = feat_dim
self.num_classes = 1 # use... | 4,510 | 34.242188 | 81 | py |
tafe-net | tafe-net-master/utils.py | import os
import re
import torch
import numpy as np
import itertools
import json
from os.path import join
import glob
import pdb
import shutil
class UnNormalizer:
def __init__(self, mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]):
self.mean = mean
self.std = std
def __call__(self, tens... | 4,192 | 27.719178 | 78 | py |
tafe-net | tafe-net-master/compositional-zs/train_compose.py | import torch
import torch.nn as nn
import torch.backends.cudnn as cudnn
import torch.utils.checkpoint
import argparse
import logging
from tqdm import tqdm
import time
import models
from utils import *
from .compose_data import CompositionDataset
def parse_args():
parser = argparse.ArgumentParser()
parser.ad... | 15,249 | 39.131579 | 80 | py |
tafe-net | tafe-net-master/compositional-zs/compose_data.py | import torch
import torch.utils.data as data
from os.path import join, exists
def load_word_embeddings(emb_file, vocab):
vocab = [v.lower() for v in vocab]
embeds = {}
for line in open(emb_file, 'r'):
line = line.strip().split(' ')
wvec = torch.FloatTensor(list(map(float, line[1:])))
... | 5,830 | 36.140127 | 80 | py |
tafe-net | tafe-net-master/zero-shot/train_zsl.py | import torch
import torch.nn as nn
import torch.backends.cudnn as cudnn
import torch.utils.checkpoint
import argparse
import logging
import models
from .zsl_data import ZSData
from utils import *
from tqdm import tqdm
import time
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument('--arc... | 16,199 | 39.09901 | 80 | py |
tafe-net | tafe-net-master/zero-shot/zsl_data.py | from scipy.io import loadmat
import torch
import torch.utils.data as data
import torchvision.transforms as transforms
from torchvision.datasets.folder import default_loader
from PIL import Image
import numpy as np
import os
from os.path import join, exists
import pickle
import pdb
class ZSData(data.Dataset):
def ... | 2,600 | 33.223684 | 79 | py |
DLDR | DLDR-main/main.py | import argparse
import os
import random
import shutil
import time
import warnings
import os
import numpy as np
import pickle
from PIL import Image, ImageFile
ImageFile.LOAD_TRUNCATED_IMAGES = True
import torch
import torch.nn as nn
import torch.nn.parallel
import torch.backends.cudnn as cudnn
import torch.distribute... | 18,827 | 36.656 | 118 | py |
DLDR | DLDR-main/train_pbfgs_imagenet.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 as optim
import torch.utils.data
import torchvision.transforms as transforms
import torchvision.datasets as datasets
import torchvision.models as model... | 14,722 | 31.358242 | 103 | py |
DLDR | DLDR-main/train_pbfgs.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 as optim
import torch.utils.data
import torchvision.transforms as transforms
import torchvision.datasets as datasets
import torchvision.models as model... | 14,990 | 31.518438 | 103 | py |
DLDR | DLDR-main/resnet.py | '''
Properly implemented ResNet-s for CIFAR10 as described in paper [1].
The implementation and structure of this file is hugely influenced by [2]
which is implemented for ImageNet and doesn't have option A for identity.
Moreover, most of the implementations on the web is copy-paste from
torchvision's resnet and has w... | 5,247 | 31.395062 | 120 | py |
DLDR | DLDR-main/utils.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 as optim
import torch.utils.data
import torch.nn.functional as F
import torchvision.transforms as transforms
import torchvision.datasets as datasets
im... | 18,120 | 39.358575 | 108 | py |
DLDR | DLDR-main/train_psgd.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 as optim
import torch.utils.data
import torchvision.transforms as transforms
import torchvision.datasets as datasets
from sklearn.decomposition import... | 13,263 | 31.750617 | 109 | py |
DLDR | DLDR-main/train_sgd.py | import argparse
import os
import shutil
import time
import numpy as np
import pickle
import random
import torch
import torch.nn as nn
import torch.nn.parallel
import torch.backends.cudnn as cudnn
import torch.optim
import torch.utils.data
import torchvision.transforms as transforms
import torchvision.datasets as datas... | 13,237 | 33.473958 | 115 | py |
DLDR | DLDR-main/models/shufflenetv2.py | """shufflenetv2 in pytorch
[1] Ningning Ma, Xiangyu Zhang, Hai-Tao Zheng, Jian Sun
ShuffleNet V2: Practical Guidelines for Efficient CNN Architecture Design
https://arxiv.org/abs/1807.11164
"""
import torch
import torch.nn as nn
import torch.nn.functional as F
def channel_split(x, split):
"""split a ... | 4,794 | 28.96875 | 101 | py |
DLDR | DLDR-main/models/inceptionv4.py | # -*- coding: UTF-8 -*-
""" inceptionv4 in pytorch
[1] Christian Szegedy, Sergey Ioffe, Vincent Vanhoucke, Alex Alemi
Inception-v4, Inception-ResNet and the Impact of Residual Connections on Learning
https://arxiv.org/abs/1602.07261
"""
import torch
import torch.nn as nn
class BasicConv2d(nn.Module):
... | 18,093 | 31.838475 | 109 | py |
DLDR | DLDR-main/models/efficientnet.py | import torch.nn as nn
import math
import torch.nn as nn
import torch
import torch.nn.functional as F
class conv_bn_act(nn.Module):
def __init__(self, inchannels, outchannels, kernelsize, stride=1, dilation=1, groups=1, bias=False, bn_momentum=0.99):
super().__init__()
self.block = nn.Sequential(... | 7,792 | 37.389163 | 123 | py |
DLDR | DLDR-main/models/resnet.py | """resnet in pytorch
[1] Kaiming He, Xiangyu Zhang, Shaoqing Ren, Jian Sun.
Deep Residual Learning for Image Recognition
https://arxiv.org/abs/1512.03385v1
"""
import torch
import torch.nn as nn
class BasicBlock(nn.Module):
"""Basic Block for resnet 18 and resnet 34
"""
#BasicBlock and Bottl... | 5,479 | 32.414634 | 118 | py |
DLDR | DLDR-main/models/mobilenetv2.py | """mobilenetv2 in pytorch
[1] Mark Sandler, Andrew Howard, Menglong Zhu, Andrey Zhmoginov, Liang-Chieh Chen
MobileNetV2: Inverted Residuals and Linear Bottlenecks
https://arxiv.org/abs/1801.04381
"""
import torch
import torch.nn as nn
import torch.nn.functional as F
class LinearBottleNeck(nn.Module):
... | 2,817 | 26.627451 | 109 | py |
DLDR | DLDR-main/models/squeezenet.py | """squeezenet in pytorch
[1] Song Han, Jeff Pool, John Tran, William J. Dally
squeezenet: Learning both Weights and Connections for Efficient Neural Networks
https://arxiv.org/abs/1506.02626
"""
import torch
import torch.nn as nn
class Fire(nn.Module):
def __init__(self, in_channel, out_channel, squ... | 2,447 | 23.979592 | 83 | py |
DLDR | DLDR-main/models/vgg.py | """vgg in pytorch
[1] Karen Simonyan, Andrew Zisserman
Very Deep Convolutional Networks for Large-Scale Image Recognition.
https://arxiv.org/abs/1409.1556v6
"""
'''VGG11/13/16/19 in Pytorch.'''
import torch
import torch.nn as nn
cfg = {
'A' : [64, 'M', 128, 'M', 256, 256, 'M', 512, 5... | 2,039 | 25.842105 | 114 | py |
DLDR | DLDR-main/models/preactresnet.py | """preactresnet in pytorch
[1] Kaiming He, Xiangyu Zhang, Shaoqing Ren, Jian Sun
Identity Mappings in Deep Residual Networks
https://arxiv.org/abs/1603.05027
"""
import torch
import torch.nn as nn
import torch.nn.functional as F
class PreActBasic(nn.Module):
expansion = 1
def __init__(self, in_chan... | 3,897 | 28.530303 | 111 | py |
DLDR | DLDR-main/models/densenet.py | """dense net in pytorch
[1] Gao Huang, Zhuang Liu, Laurens van der Maaten, Kilian Q. Weinberger.
Densely Connected Convolutional Networks
https://arxiv.org/abs/1608.06993v5
"""
import torch
import torch.nn as nn
#"""Bottleneck layers. Although each layer only produces k
#output feature-maps, it typicall... | 5,074 | 37.740458 | 147 | py |
DLDR | DLDR-main/models/googlenet.py | """google net in pytorch
[1] Christian Szegedy, Wei Liu, Yangqing Jia, Pierre Sermanet, Scott Reed,
Dragomir Anguelov, Dumitru Erhan, Vincent Vanhoucke, Andrew Rabinovich.
Going Deeper with Convolutions
https://arxiv.org/abs/1409.4842v1
"""
import torch
import torch.nn as nn
class Inception(nn.Module)... | 4,493 | 31.1 | 94 | py |
DLDR | DLDR-main/models/resnext.py | """resnext in pytorch
[1] Saining Xie, Ross Girshick, Piotr Dollár, Zhuowen Tu, Kaiming He.
Aggregated Residual Transformations for Deep Neural Networks
https://arxiv.org/abs/1611.05431
"""
import math
import torch
import torch.nn as nn
import torch.nn.functional as F
#only implements ResNext bottleneck c... | 4,194 | 31.022901 | 99 | py |
DLDR | DLDR-main/models/senet.py | """senet in pytorch
[1] Jie Hu, Li Shen, Samuel Albanie, Gang Sun, Enhua Wu
Squeeze-and-Excitation Networks
https://arxiv.org/abs/1709.01507
"""
import torch
import torch.nn as nn
import torch.nn.functional as F
class BasicResidualSEBlock(nn.Module):
expansion = 1
def __init__(self, in_channels,... | 5,231 | 29.418605 | 89 | py |
DLDR | DLDR-main/models/shufflenet.py | """shufflenet in pytorch
[1] Xiangyu Zhang, Xinyu Zhou, Mengxiao Lin, Jian Sun.
ShuffleNet: An Extremely Efficient Convolutional Neural Network for Mobile Devices
https://arxiv.org/abs/1707.01083v2
"""
from functools import partial
import torch
import torch.nn as nn
class BasicConv2d(nn.Module):
de... | 7,438 | 27.945525 | 91 | py |
DLDR | DLDR-main/models/nasnet.py | """nasnet in pytorch
[1] Barret Zoph, Vijay Vasudevan, Jonathon Shlens, Quoc V. Le
Learning Transferable Architectures for Scalable Image Recognition
https://arxiv.org/abs/1707.07012
"""
import torch
import torch.nn as nn
class SeperableConv2d(nn.Module):
def __init__(self, input_channels, output_cha... | 9,594 | 28.164134 | 125 | py |
DLDR | DLDR-main/models/wideresidual.py | import torch
import torch.nn as nn
class WideBasic(nn.Module):
def __init__(self, in_channels, out_channels, stride=1):
super().__init__()
self.residual = nn.Sequential(
nn.BatchNorm2d(in_channels),
nn.ReLU(inplace=True),
nn.Conv2d(
in_channels,... | 3,255 | 30.307692 | 76 | py |
DLDR | DLDR-main/models/xception.py | """xception in pytorch
[1] François Chollet
Xception: Deep Learning with Depthwise Separable Convolutions
https://arxiv.org/abs/1610.02357
"""
import torch
import torch.nn as nn
class SeperableConv2d(nn.Module):
#***Figure 4. An “extreme” version of our Inception module,
#with one spatial convolut... | 6,107 | 25.789474 | 82 | py |
DLDR | DLDR-main/models/rir.py | """resnet in resnet in pytorch
[1] Sasha Targ, Diogo Almeida, Kevin Lyman.
Resnet in Resnet: Generalizing Residual Architectures
https://arxiv.org/abs/1603.08029v1
"""
import torch
import torch.nn as nn
#geralized
class ResnetInit(nn.Module):
def __init__(self, in_channel, out_channel, stride):
... | 7,033 | 38.965909 | 114 | py |
DLDR | DLDR-main/models/mobilenet.py | """mobilenet in pytorch
[1] Andrew G. Howard, Menglong Zhu, Bo Chen, Dmitry Kalenichenko, Weijun Wang, Tobias Weyand, Marco Andreetto, Hartwig Adam
MobileNets: Efficient Convolutional Neural Networks for Mobile Vision Applications
https://arxiv.org/abs/1704.04861
"""
import torch
import torch.nn as nn
cl... | 5,314 | 24.070755 | 123 | py |
DLDR | DLDR-main/models/attention.py | """residual attention network in pytorch
[1] Fei Wang, Mengqing Jiang, Chen Qian, Shuo Yang, Cheng Li, Honggang Zhang, Xiaogang Wang, Xiaoou Tang
Residual Attention Network for Image Classification
https://arxiv.org/abs/1704.06904
"""
import torch
import torch.nn as nn
import torch.nn.functional as F
#"""... | 11,757 | 32.594286 | 120 | py |
DLDR | DLDR-main/models/stochasticdepth.py | """
resnet with stochastic depth
[1] Gao Huang, Yu Sun, Zhuang Liu, Daniel Sedra, Kilian Weinberger
Deep Networks with Stochastic Depth
https://arxiv.org/abs/1603.09382v3
"""
import torch
import torch.nn as nn
from torch.distributions.bernoulli import Bernoulli
import random
class StochasticDepthBasicBlock(... | 7,512 | 35.294686 | 133 | py |
DLDR | DLDR-main/models/inceptionv3.py | """ inceptionv3 in pytorch
[1] Christian Szegedy, Vincent Vanhoucke, Sergey Ioffe, Jonathon Shlens, Zbigniew Wojna
Rethinking the Inception Architecture for Computer Vision
https://arxiv.org/abs/1512.00567v3
"""
import torch
import torch.nn as nn
class BasicConv2d(nn.Module):
def __init__(self, input... | 10,872 | 31.360119 | 90 | py |
CRF-AE | CRF-AE-master/main.py | import torch
import torch.nn as nn
import torch.nn.functional as F
from torch import autograd
from torch.optim import lr_scheduler
from sklearn.metrics import f1_score
from torch import optim
from tqdm import tqdm
import optparse
import itertools
import loader
import time
import numpy as np
import datetime
import pic... | 12,535 | 38.175 | 189 | py |
CRF-AE | CRF-AE-master/utils.py | from __future__ import print_function
import os
import re
import numpy as np
models_path = "./models"
eval_path = "./evaluation"
eval_temp = os.path.join(eval_path, "temp")
eval_script = os.path.join(eval_path, "conlleval")
def get_name(parameters):
"""
Generate a model name from its parameters.
"""
... | 8,346 | 29.914815 | 85 | py |
CRF-AE | CRF-AE-master/model.py | import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.autograd as autograd
from torch.autograd import Variable
from utils import *
from config import parameters
START_TAG = '<START>'
STOP_TAG = '<STOP>'
def to_scalar(var):
return var.view(-1).data.tolist()[0]
def argmax(vec):
_, id... | 10,187 | 44.28 | 151 | py |
CRF-AE | CRF-AE-master/config.py |
import torch
from collections import OrderedDict
parameters = OrderedDict()
parameters['tag_scheme'] = "iobes"
parameters['lower'] = True
parameters['zeros'] = False
parameters['char_dim'] = 25
parameters['char_lstm_dim'] = 25
parameters['char_bidirect'] = True
parameters['word_dim'] = 300
parameters['word_lstm_dim']... | 1,430 | 30.8 | 65 | py |
CRF-AE | CRF-AE-master/loader.py | from __future__ import print_function, division
import os
import re
import codecs
import unicodedata
from utils import create_dico, create_mapping, zero_digits
from utils import iob2, iob_iobes
import model
import string
import random
import numpy as np
def unicodeToAscii(s):
return ''.join(
c for c in un... | 11,016 | 31.691395 | 110 | py |
sisl | sisl-main/docs/conf.py | # This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at https://mozilla.org/MPL/2.0/.
#
# sisl documentation build configuration file, created by
# sphinx-quickstart on Wed Dec 2 19:55:34 2015.
#
# This fi... | 12,821 | 30.895522 | 235 | py |
RoCL | RoCL-master/src/data_loader.py | import torch
from data.cifar import CIFAR10, CIFAR100
from torchvision import transforms
def get_dataset(args):
### color augmentation ###
color_jitter = transforms.ColorJitter(0.8*args.color_jitter_strength, 0.8*args.color_jitter_strength, 0.8*args.color_jitter_strength, 0.2*args.color_jitter_strength)
... | 6,089 | 37.544304 | 169 | py |
RoCL | RoCL-master/src/loss.py | import diffdist.functional as distops
import torch
import torch.distributed as dist
def pairwise_similarity(outputs,temperature=0.5,multi_gpu=False, adv_type='None'):
'''
Compute pairwise similarity and return the matrix
input: aggregated outputs & temperature for scaling
return: pairwise c... | 3,325 | 37.674419 | 138 | py |
RoCL | RoCL-master/src/utils.py | '''Some helper functions for PyTorch, including:
- get_mean_and_std: calculate the mean and std value of dataset.
- msr_init: net parameter initialization.
- progress_bar: progress bar mimic xlua.progress.
'''
import os
import sys
import time
import math
import torch
import torch.nn as nn
import torch.nn.i... | 6,514 | 28.346847 | 223 | py |
RoCL | RoCL-master/src/robustness_test.py | #!/usr/bin/env python3 -u
from __future__ import print_function
import csv
import os
import torch
import torch.backends.cudnn as cudnn
import torch.nn as nn
import data_loader
import model_loader
from utils import progress_bar
from collections import OrderedDict
from attack_lib import FastGradientSignUntargeted
a... | 4,858 | 28.271084 | 227 | py |
RoCL | RoCL-master/src/rocl_train.py | #!/usr/bin/env python3 -u
from __future__ import print_function
import csv
import os
import torch
import torch.backends.cudnn as cudnn
import torch.optim as optim
import data_loader
import model_loader
from attack_lib import FastGradientSignUntargeted,RepresentationAdv
from models.projector import Projector
from ... | 7,591 | 33.044843 | 244 | py |
RoCL | RoCL-master/src/linear_eval.py | #!/usr/bin/env python3 -u
from __future__ import print_function
import argparse
import csv
import os
import json
import copy
import numpy as np
import torch
from torch.autograd import Variable
import torch.backends.cudnn as cudnn
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
impor... | 10,011 | 30.093168 | 255 | py |
RoCL | RoCL-master/src/attack_lib.py | """
this code is modified from
https://github.com/utkuozbulak/pytorch-cnn-adversarial-attacks
https://github.com/louis2889184/pytorch-adversarial-training
https://github.com/MadryLab/robustness
https://github.com/yaodongyu/TRADES
"""
import torch
import torch.nn.functional as F
from loss import pairwise_similarity,... | 6,873 | 36.358696 | 141 | py |
RoCL | RoCL-master/src/models/projector.py | import torch
import torch.nn as nn
import torch.nn.functional as F
class Projector(nn.Module):
def __init__(self, expansion=0):
super(Projector, self).__init__()
self.linear_1 = nn.Linear(512*expansion, 2048)
self.linear_2 = nn.Linear(2048, 128)
def forward(self, x):
... | 458 | 20.857143 | 54 | py |
RoCL | RoCL-master/src/models/resnet.py | '''ResNet in PyTorch.
BasicBlock and Bottleneck module is from the original ResNet paper:
[1] Kaiming He, Xiangyu Zhang, Shaoqing Ren, Jian Sun
Deep Residual Learning for Image Recognition. arXiv:1512.03385
PreActBlock and PreActBottleneck module is from the later paper:
[2] Kaiming He, Xiangyu Zhang, Shaoqing Re... | 6,827 | 34.5625 | 108 | py |
RoCL | RoCL-master/src/warmup_scheduler/run.py | import torch
from warmup_scheduler import GradualWarmupScheduler
if __name__ == '__main__':
v = torch.zeros(10)
optim = torch.optim.SGD([v], lr=0.01)
scheduler = GradualWarmupScheduler(optim, multiplier=8, total_epoch=10)
for epoch in range(1, 20):
scheduler.step(epoch)
print(epoch,... | 350 | 22.4 | 75 | py |
RoCL | RoCL-master/src/warmup_scheduler/scheduler.py | from torch.optim.lr_scheduler import _LRScheduler
from torch.optim.lr_scheduler import ReduceLROnPlateau
class GradualWarmupScheduler(_LRScheduler):
""" Gradually warm-up(increasing) learning rate in optimizer.
Proposed in 'Accurate, Large Minibatch SGD: Training ImageNet in 1 Hour'.
Args:
optimi... | 3,069 | 46.96875 | 152 | py |
RoCL | RoCL-master/src/data/utils.py | import os
import os.path
import hashlib
import gzip
import errno
import tarfile
import zipfile
import torch
from torch.utils.model_zoo import tqdm
from torch._six import PY3
def gen_bar_updater():
pbar = tqdm(total=None)
def bar_update(count, block_size, total_size):
if pbar.total is None and total_... | 9,098 | 29.94898 | 109 | py |
RoCL | RoCL-master/src/data/vision.py | import os
import torch
import torch.utils.data as data
class VisionDataset(data.Dataset):
_repr_indent = 4
def __init__(self, root, transforms=None, transform=None, target_transform=None):
if isinstance(root, torch._six.string_classes):
root = os.path.expanduser(root)
self.root = ... | 2,950 | 35.432099 | 86 | py |
RoCL | RoCL-master/src/data/cifar.py | from __future__ import print_function
from PIL import Image
import os
import os.path
import numpy as np
import sys
from torchvision import transforms
if sys.version_info[0] == 2:
import cPickle as pickle
else:
import pickle
from .vision import VisionDataset
from .utils import check_integrity, download_and_extr... | 7,214 | 34.895522 | 99 | py |
RSP | RSP-main/Change Detection/visualization.py | '''
This file is used to save the output image
'''
import torch.utils.data
from utils.parser import get_parser_with_args
from utils.helpers import get_test_loaders, initialize_metrics
import os
from tqdm import tqdm
import cv2
# if not os.path.exists('./output_img'):
# os.mkdir('./output_img')
parser, metadata =... | 1,623 | 24.777778 | 77 | py |
RSP | RSP-main/Change Detection/eval.py | import torch.utils.data
from utils.parser import get_parser_with_args
from utils.helpers import get_test_loaders
from tqdm import tqdm
from sklearn.metrics import confusion_matrix
# The Evaluation Methods in our paper are slightly different from this file.
# In our paper, we use the evaluation methods in train.py. spe... | 1,898 | 31.186441 | 98 | py |
RSP | RSP-main/Change Detection/train.py | from cProfile import label
import datetime
import torch
from sklearn.metrics import precision_recall_fscore_support as prfs
from utils.parser import get_parser_with_args
from utils.helpers import (get_loaders, get_criterion,
load_model, initialize_metrics, get_mean_metrics,
... | 8,901 | 35.040486 | 182 | py |
RSP | RSP-main/Change Detection/models/siamunet_dif.py | # Rodrigo Caye Daudt
# https://rcdaudt.github.io/
# Daudt, R. C., Le Saux, B., & Boulch, A. "Fully convolutional siamese networks for change detection". In 2018 25th IEEE International Conference on Image Processing (ICIP) (pp. 4063-4067). IEEE.
import torch
import torch.nn as nn
import torch.nn.functional as F
from t... | 8,121 | 44.122222 | 195 | py |
RSP | RSP-main/Change Detection/models/swin_transformer.py | # --------------------------------------------------------
# Swin Transformer
# Copyright (c) 2021 Microsoft
# Licensed under The MIT License [see LICENSE for details]
# Written by Ze Liu, Yutong Lin, Yixuan Wei
# --------------------------------------------------------
import warnings
from collections import OrderedDi... | 28,910 | 38.495902 | 142 | py |
RSP | RSP-main/Change Detection/models/resnet.py | import math
import torch
import torch.nn as nn
import torch.utils.model_zoo as model_zoo
import os
import torchvision
torchvision.models.resnext50_32x4d()
from mmcv.cnn import (constant_init, kaiming_init)
#from ..backbones.custom_load import load_checkpoint
#from mmcv.utils.registry import BACKBONES
import warning... | 18,012 | 38.073753 | 131 | py |
RSP | RSP-main/Change Detection/models/networks.py | import torch
import torch.nn as nn
from torch.nn import init
import torch.nn.functional as F
from torch.optim import lr_scheduler
import functools
from einops import rearrange
import models
class TwoLayerConv2d(nn.Sequential):
def __init__(self, in_channels, out_channels, kernel_size=3):
super().__init__... | 22,619 | 37.145025 | 128 | py |
RSP | RSP-main/Change Detection/models/Models.py | # Kaiyu Li
# https://github.com/likyoo
#
import torch.nn as nn
import torch
class conv_block_nested(nn.Module):
def __init__(self, in_ch, mid_ch, out_ch):
super(conv_block_nested, self).__init__()
self.activation = nn.ReLU(inplace=True)
self.conv1 = nn.Conv2d(in_ch, mid_ch, kernel_size=3, ... | 13,738 | 40.134731 | 103 | py |
RSP | RSP-main/Change Detection/models/ViTAE_Window_NoShift/base_model.py | from functools import partial
from pyexpat import model
import torch
import torch.nn as nn
from timm.models.layers import trunc_normal_
import numpy as np
from torch.nn.functional import instance_norm
from torch.nn.modules.batchnorm import BatchNorm2d
from .NormalCell import NormalCell
from .ReductionCell import Reduct... | 17,793 | 44.048101 | 199 | py |
RSP | RSP-main/Change Detection/models/ViTAE_Window_NoShift/swin.py | # --------------------------------------------------------
# Swin Transformer
# Copyright (c) 2021 Microsoft
# Licensed under The MIT License [see LICENSE for details]
# Written by Ze Liu
# --------------------------------------------------------
import torch
import torch.nn as nn
import torch.utils.checkpoint as chec... | 24,644 | 40.559865 | 142 | py |
RSP | RSP-main/Change Detection/models/ViTAE_Window_NoShift/ReductionCell.py | import math
from numpy.core.fromnumeric import resize, shape
import torch
import torch.nn as nn
import torch.nn.functional as F
from timm.models.layers import DropPath, to_2tuple, trunc_normal_
import numpy as np
from .token_transformer import Token_transformer
from .token_performer import Token_performer
from .SELayer... | 11,032 | 46.761905 | 179 | py |
RSP | RSP-main/Change Detection/models/ViTAE_Window_NoShift/NormalCell.py | # Copyright (c) [2012]-[2021] Shanghai Yitu Technology Co., Ltd.
#
# This source code is licensed under the Clear BSD License
# LICENSE file in the root directory of this file
# All rights reserved.
"""
Borrow from timm(https://github.com/rwightman/pytorch-image-models)
"""
import torch
import torch.nn as nn
import num... | 11,944 | 43.240741 | 177 | py |
RSP | RSP-main/Change Detection/models/ViTAE_Window_NoShift/token_performer.py | """
Take Performer as T2T Transformer
"""
import math
import torch
import torch.nn as nn
import numpy as np
class Token_performer(nn.Module):
def __init__(self, dim, in_dim, head_cnt=1, kernel_ratio=0.5, dp1=0.1, dp2 = 0.1, gamma=False, init_values=1e-4):
super().__init__()
self.head_dim = in_dim ... | 3,147 | 35.604651 | 128 | py |
RSP | RSP-main/Change Detection/models/ViTAE_Window_NoShift/SELayer.py | import torch
import torch.nn as nn
class SELayer(nn.Module):
def __init__(self, channel, reduction=16):
super(SELayer, self).__init__()
self.avg_pool = nn.AdaptiveAvgPool1d(1)
self.fc = nn.Sequential(
nn.Linear(channel, channel // reduction, bias=False),
nn.ReLU(inpl... | 726 | 32.045455 | 65 | py |
RSP | RSP-main/Change Detection/models/ViTAE_Window_NoShift/token_transformer.py | # Copyright (c) [2012]-[2021] Shanghai Yitu Technology Co., Ltd.
#
# This source code is licensed under the Clear BSD License
# LICENSE file in the root directory of this file
# All rights reserved.
"""
Take the standard Transformer as T2T Transformer
"""
import torch
import torch.nn as nn
from timm.models.layers impor... | 2,703 | 39.358209 | 165 | py |
RSP | RSP-main/Change Detection/models/ViTAE_Window_NoShift/models.py | # Copyright (c) [2012]-[2021] Shanghai Yitu Technology Co., Ltd.
#
# This source code is licensed under the Clear BSD License
# LICENSE file in the root directory of this file
# All rights reserved.
"""
T2T-ViT
"""
from math import gamma
import torch
import torch.nn as nn
from timm.models.helpers import load_pretraine... | 1,657 | 38.47619 | 269 | py |
RSP | RSP-main/Change Detection/utils/dataloaders.py | import os
import torch.utils.data as data
from PIL import Image
from utils import transforms as tr
'''
Load all training and validation data paths
'''
def full_path_loader(data_dir):
train_data = [i for i in os.listdir(data_dir + 'train/A/') if not
i.startswith('.')]
train_data.sort()
valid_data = [i... | 3,453 | 25.775194 | 93 | py |
RSP | RSP-main/Change Detection/utils/metrics.py | import torch
import torch.utils.data
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Variable
class FocalLoss(nn.Module):
def __init__(self, gamma=0, alpha=None, size_average=True):
super(FocalLoss, self).__init__()
self.gamma = gamma
self.alpha = alpha
... | 6,699 | 38.181287 | 73 | py |
RSP | RSP-main/Change Detection/utils/helpers.py | import logging
import torch
import torch.utils.data
import torch.nn as nn
import numpy as np
from utils.dataloaders import (full_path_loader, full_test_loader, CDDloader, LEVIRloader)
from utils.metrics import jaccard_loss, dice_loss
from utils.losses import hybrid_loss
from models.Models import Siam_NestedUNet_Conc, S... | 5,439 | 26.614213 | 92 | py |
RSP | RSP-main/Change Detection/utils/transforms.py | import torch
import random
import numpy as np
from PIL import Image, ImageOps, ImageFilter
import torchvision.transforms as transforms
class Normalize(object):
"""Normalize a tensor image with mean and standard deviation.
Args:
mean (tuple): means for each channel.
std (tuple): standard deviat... | 7,680 | 32.251082 | 92 | py |
RSP | RSP-main/Semantic Segmentation/tools/test.py | # Copyright (c) OpenMMLab. All rights reserved.
import argparse
import os
import os.path as osp
import shutil
import time
import warnings
import mmcv
import torch
from mmcv.cnn.utils import revert_sync_batchnorm
from mmcv.parallel import MMDataParallel, MMDistributedDataParallel
from mmcv.runner import (get_dist_info,... | 11,983 | 38.421053 | 79 | py |
RSP | RSP-main/Semantic Segmentation/tools/benchmark.py | # Copyright (c) OpenMMLab. All rights reserved.
import argparse
import os.path as osp
import time
import mmcv
import numpy as np
import torch
from mmcv import Config
from mmcv.parallel import MMDataParallel
from mmcv.runner import load_checkpoint, wrap_fp16_model
from mmseg.datasets import build_dataloader, build_dat... | 4,328 | 34.77686 | 79 | py |
RSP | RSP-main/Semantic Segmentation/tools/onnx2tensorrt.py | # Copyright (c) OpenMMLab. All rights reserved.
import argparse
import os
import os.path as osp
from typing import Iterable, Optional, Union
import matplotlib.pyplot as plt
import mmcv
import numpy as np
import onnxruntime as ort
import torch
from mmcv.ops import get_onnxruntime_op_path
from mmcv.tensorrt import (TRTW... | 9,334 | 32.700361 | 79 | py |
RSP | RSP-main/Semantic Segmentation/tools/publish_model.py | # Copyright (c) OpenMMLab. All rights reserved.
import argparse
import subprocess
import torch
def parse_args():
parser = argparse.ArgumentParser(
description='Process a checkpoint to be published')
parser.add_argument('in_file', help='input checkpoint filename')
parser.add_argument('out_file', h... | 1,076 | 28.108108 | 77 | py |
RSP | RSP-main/Semantic Segmentation/tools/pytorch2onnx.py | # Copyright (c) OpenMMLab. All rights reserved.
import argparse
from functools import partial
import mmcv
import numpy as np
import onnxruntime as rt
import torch
import torch._C
import torch.serialization
from mmcv import DictAction
from mmcv.onnx import register_extra_symbolics
from mmcv.runner import load_checkpoin... | 13,614 | 33.732143 | 79 | py |
RSP | RSP-main/Semantic Segmentation/tools/deploy_test.py | # Copyright (c) OpenMMLab. All rights reserved.
import argparse
import os
import os.path as osp
import shutil
import warnings
from typing import Any, Iterable
import mmcv
import numpy as np
import torch
from mmcv.parallel import MMDataParallel
from mmcv.runner import get_dist_info
from mmcv.utils import DictAction
fr... | 12,659 | 37.715596 | 78 | py |
RSP | RSP-main/Semantic Segmentation/tools/pytorch2torchscript.py | # Copyright (c) OpenMMLab. All rights reserved.
import argparse
import mmcv
import numpy as np
import torch
import torch._C
import torch.serialization
from mmcv.runner import load_checkpoint
from torch import nn
from mmseg.models import build_segmentor
torch.manual_seed(3)
def digit_version(version_str):
digit... | 6,057 | 31.569892 | 77 | py |
RSP | RSP-main/Semantic Segmentation/tools/train.py | # Copyright (c) OpenMMLab. All rights reserved.
import argparse
import copy
import os
import os.path as osp
import time
import warnings
import mmcv
import torch
from mmcv.cnn.utils import revert_sync_batchnorm
from mmcv.runner import get_dist_info, init_dist
from mmcv.utils import Config, DictAction, get_git_hash
fro... | 8,962 | 37.140426 | 79 | py |
RSP | RSP-main/Semantic Segmentation/tools/torchserve/mmseg_handler.py | # Copyright (c) OpenMMLab. All rights reserved.
import base64
import os
import cv2
import mmcv
import torch
from mmcv.cnn.utils.sync_bn import revert_sync_batchnorm
from ts.torch_handler.base_handler import BaseHandler
from mmseg.apis import inference_segmentor, init_segmentor
class MMsegHandler(BaseHandler):
... | 1,867 | 31.77193 | 79 | py |
RSP | RSP-main/Semantic Segmentation/tools/torchserve/test_torchserve.py | from argparse import ArgumentParser
from io import BytesIO
import matplotlib.pyplot as plt
import mmcv
import requests
from mmseg.apis import inference_segmentor, init_segmentor
def parse_args():
parser = ArgumentParser(
description='Compare result of torchserve and pytorch,'
'and visualize them... | 1,747 | 29.137931 | 77 | py |
RSP | RSP-main/Semantic Segmentation/tools/torchserve/mmseg2torchserve.py | # Copyright (c) OpenMMLab. All rights reserved.
from argparse import ArgumentParser, Namespace
from pathlib import Path
from tempfile import TemporaryDirectory
import mmcv
try:
from model_archiver.model_packaging import package_model
from model_archiver.model_packaging_utils import ModelExportUtils
except Imp... | 3,700 | 32.044643 | 76 | py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.