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
benchmark-rrc
benchmark-rrc-master/python/residual_learning/networks.py
"""Define networks and ResidualPPO2.""" from dl.rl import PolicyBase, ContinuousQFunctionBase from dl.rl import Policy, QFunction from dl import nest, TanhDiagGaussian import torch import torch.nn as nn import numpy as np from residual_learning import modules import gin @gin.configurable class NetworkParams(object): ...
6,326
34.948864
87
py
benchmark-rrc
benchmark-rrc-master/python/residual_learning/make_training_env.py
"""Define training env.""" import torch import gin import os from dl.rl.envs import SubprocVecEnv, DummyVecEnv, EpisodeInfo, VecObsNormWrapper from env.make_env import make_env from trifinger_simulation.tasks import move_cube from .residual_wrappers import ResidualWrapper, RandomizedEnvWrapper @gin.configurable def m...
2,440
34.897059
143
py
benchmark-rrc
benchmark-rrc-master/python/residual_learning/eval.py
"""Visualize a learned residual controller. """ from residual_learning.residual_sac import ResidualSAC import dl import os import torch import numpy as np from dl import nest import argparse import yaml from scipy.spatial.transform import Rotation as R def _load_env_and_policy(logdir, t=None): gin_bindings = [ ...
4,164
29.181159
103
py
benchmark-rrc
benchmark-rrc-master/python/residual_learning/viz.py
"""Visualize a learned residual controller. """ from residual_learning.residual_sac import ResidualSAC import dl import os import torch import numpy as np from dl import nest import argparse from imageio import imwrite import tempfile import subprocess as sp import shutil class VideoWriter(object): def __init__(s...
4,430
29.142857
103
py
benchmark-rrc
benchmark-rrc-master/python/residual_learning/get_ob_norm.py
import argparse from dl import nest from residual_learning.make_training_env import make_training_env from residual_learning.state_machines import MPPGStateMachine import torch import numpy as np import os def get_norm_params(n, difficulty, use_domain_rand): term_fn = 'position_close_to_goal' if difficulty < 4 el...
3,282
34.301075
89
py
benchmark-rrc
benchmark-rrc-master/python/residual_learning/residual_sac.py
"""SAC algorithm. https://arxiv.org/abs/1801.01290 """ from dl.rl.data_collection import ReplayBufferDataManager, ReplayBuffer from dl import logger, nest, Algorithm, Checkpointer import gin import os import time import torch import numpy as np from dl.rl.util import rl_evaluate, rl_record, misc from dl.rl.envs import...
16,113
39.084577
95
py
benchmark-rrc
benchmark-rrc-master/python/cic/bayesian_opt/eval_code_randomized.py
""" Bayesian Optimization experiment runner. Relies heavily on BoTorch. """ import os import logging import matplotlib.pyplot as plt import numpy as np import torch import random import sys # sys.path.append("../") import pickle as pkl from tqdm import tqdm import shutil from distutils.spawn import find_executable ...
12,196
32.508242
163
py
benchmark-rrc
benchmark-rrc-master/python/cic/bayesian_opt/eval_code.py
""" Bayesian Optimization experiment runner. Relies heavily on BoTorch. """ import os import logging import matplotlib.pyplot as plt import numpy as np import torch import sys # sys.path.append("../") import pickle as pkl from tqdm import tqdm import shutil from distutils.spawn import find_executable from utils.fu...
10,377
30.932308
163
py
benchmark-rrc
benchmark-rrc-master/python/cic/bayesian_opt/bayes_opt_main.py
""" Bayesian Optimization experiment runner. Relies heavily on BoTorch. """ import os import logging import matplotlib.pyplot as plt import numpy as np import torch import sys # sys.path.append("../") import pickle as pkl from botorch.models import SingleTaskGP from botorch.fit import fit_gpytorch_model from botorch...
21,312
37.892336
277
py
benchmark-rrc
benchmark-rrc-master/python/cic/bayesian_opt/utils/normalization_tools.py
# Copyright (c) 2020, Fabio Muratore, Honda Research Institute Europe GmbH, and # Technical University of Darmstadt. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # 1. Redistributions of source ...
13,593
44.61745
128
py
pidinet
pidinet-master/main.py
""" (Training, Generating edge maps) Pixel Difference Networks for Efficient Edge Detection (accepted as an ICCV 2021 oral) See paper in https://arxiv.org/abs/2108.07009 Author: Zhuo Su, Wenzhe Liu Date: Aug 22, 2020 """ from __future__ import absolute_import from __future__ import unicode_literals from __future__ im...
16,426
38.111905
161
py
pidinet
pidinet-master/edge_dataloader.py
from torch.utils import data import torchvision.transforms as transforms import os from pathlib import Path from PIL import Image import numpy as np def fold_files(foldname): """All files in the fold should have the same extern""" allfiles = os.listdir(foldname) if len(allfiles) < 1: raise ValueEr...
10,617
34.511706
115
py
pidinet
pidinet-master/utils.py
""" Utility functions for training Author: Zhuo Su, Wenzhe Liu Date: Aug 22, 2020 """ from __future__ import absolute_import from __future__ import unicode_literals from __future__ import print_function from __future__ import division import os import shutil import math import time import random import skimage impor...
4,458
26.86875
83
py
pidinet
pidinet-master/throughput.py
""" (Testing FPS) Pixel Difference Networks for Efficient Edge Detection (accepted as an ICCV 2021 oral) See paper in https://arxiv.org/abs/2108.07009 Author: Zhuo Su, Wenzhe Liu Date: Aug 22, 2020 """ from __future__ import absolute_import from __future__ import unicode_literals from __future__ import print_function...
4,524
33.541985
161
py
pidinet
pidinet-master/models/convert_pidinet.py
import torch import torch.nn as nn import torch.nn.functional as F from .config import config_model_converted def convert_pdc(op, weight): if op == 'cv': return weight elif op == 'cd': shape = weight.shape weight_c = weight.sum(dim=[2, 3]) weight = weight.view(shape[0], shape[...
2,935
38.675676
86
py
pidinet
pidinet-master/models/pidinet.py
""" Author: Zhuo Su, Wenzhe Liu Date: Feb 18, 2021 """ import math import numpy as np import torch import torch.nn as nn import torch.nn.functional as F from .ops import Conv2d from .config import config_model, config_model_converted class CSAM(nn.Module): """ Compact Spatial Attention Module """ de...
10,985
33.656151
112
py
pidinet
pidinet-master/models/hed_fps.py
""" Modified from https://github.com/xwjabc/hed/blob/master/networks.py For testing fps of hed model, run: python throughput.py --model hed -j 1 --gpu 0 --datadir /path/to/BSDS500 """ import torch import torch.nn as nn import torch.nn.functional as F import numpy as np class HED(nn.Module): """ HED network. ""...
9,107
41.362791
120
py
pidinet
pidinet-master/models/ops.py
""" Function factory for pixel difference convolutional operations. Author: Zhuo Su, Wenzhe Liu Date: Aug 23, 2020 """ import math import torch import torch.nn as nn import torch.nn.functional as F class Conv2d(nn.Module): def __init__(self, pdc, in_channels, out_channels, kernel_size, stride=1, padding=0, dilat...
4,304
42.484848
123
py
pidinet
pidinet-master/models/ops_theta.py
""" Function factory for pixel difference convolutional operations with vanilla conv components please see line 49, the theta parameter was also used in "Yu et al, Searching central difference convolutional networks for face anti-spoofing, CVPR 2020" Author: Zhuo Su Date: Dec 29, 2021 """ import math import torch imp...
4,783
45
154
py
PAMA
PAMA-main/main.py
import os import sys import argparse import logging import torch import torch.nn as nn import torch.utils.data as data from torchvision.utils import save_image from PIL import Image, ImageFile from net import Net from utils import DEVICE, train_transform, test_transform, FlatFolderDataset, InfiniteSamplerWrapper, plot_...
7,336
42.672619
138
py
PAMA
PAMA-main/utils.py
import os import numpy as np import torch import torch.nn as nn import torch.nn.functional as F import torch.utils.data as data from torchvision import transforms import PIL.Image as Image DEVICE = 'cuda' mse = nn.MSELoss() def calc_histogram_loss(A, B, histogram_block): input_hist = histogram_block(A) targe...
4,904
28.023669
87
py
PAMA
PAMA-main/hist_loss.py
""" Copyright 2021 Mahmoud Afifi. Mahmoud Afifi, Marcus A. Brubaker, and Michael S. Brown. "HistoGAN: Controlling Colors of GAN-Generated and Real Images via Color Histograms." In CVPR, 2021. @inproceedings{afifi2021histogan, title={Histo{GAN}: Controlling Colors of {GAN}-Generated and Real Images via Color...
9,071
42.615385
81
py
PAMA
PAMA-main/net.py
import torch import torch.nn as nn from utils import mean_variance_norm, DEVICE from utils import calc_ss_loss, calc_remd_loss, calc_moment_loss, calc_mse_loss, calc_histogram_loss from hist_loss import RGBuvHistBlock import torch class Net(nn.Module): def __init__(self, args): super(Net, self).__init__() ...
11,282
39.010638
151
py
transferlearning
transferlearning-master/code/DeepDA/main.py
import configargparse import data_loader import os import torch import models import utils from utils import str2bool import numpy as np import random import time import wandb def get_parser(): """Get default arguments.""" parser = configargparse.ArgumentParser( description="Transfer learning config ...
10,325
39.494118
155
py
transferlearning
transferlearning-master/code/DeepDA/data_loader.py
from torchvision import datasets, transforms import torch def load_data(data_folder, batch_size, train, num_workers=0, **kwargs): transform = { 'train': transforms.Compose( [transforms.Resize([224, 224]), transforms.ToTensor(), transforms.Normalize(mean=[0.485, 0...
2,724
39.671642
144
py
transferlearning
transferlearning-master/code/DeepDA/transfer_losses.py
import torch import torch.nn as nn from loss_funcs import * class TransferLoss(nn.Module): def __init__(self, loss_type, **kwargs): super(TransferLoss, self).__init__() if loss_type == "mmd": self.loss_func = MMDLoss(**kwargs) elif loss_type == "lmmd": self.loss_func...
831
35.173913
70
py
transferlearning
transferlearning-master/code/DeepDA/models.py
import torch import torch.nn as nn from transfer_losses import TransferLoss import backbones class TransferNet(nn.Module): def __init__(self, num_class, base_net='resnet50', transfer_loss='mmd', use_bottleneck=True, bottleneck_width=256, max_iter=1000, **kwargs): super(TransferNet, self).__init__() ...
3,679
39.888889
144
py
transferlearning
transferlearning-master/code/DeepDA/backbones.py
import torch.nn as nn from torchvision import models resnet_dict = { "resnet18": models.resnet18, "resnet34": models.resnet34, "resnet50": models.resnet50, "resnet101": models.resnet101, "resnet152": models.resnet152, } def get_backbone(name): if "resnet" in name.lower(): return ResNet...
2,629
28.550562
67
py
transferlearning
transferlearning-master/code/DeepDA/loss_funcs/adv.py
import torch import torch.nn as nn from torch.autograd import Function import torch.nn.functional as F import numpy as np class LambdaSheduler(nn.Module): def __init__(self, gamma=1.0, max_iter=1000, **kwargs): super(LambdaSheduler, self).__init__() self.gamma = gamma self.max_iter = max_it...
2,495
31.415584
87
py
transferlearning
transferlearning-master/code/DeepDA/loss_funcs/mmd.py
import torch import torch.nn as nn class MMDLoss(nn.Module): def __init__(self, kernel_type='rbf', kernel_mul=2.0, kernel_num=5, fix_sigma=None, **kwargs): super(MMDLoss, self).__init__() self.kernel_num = kernel_num self.kernel_mul = kernel_mul self.fix_sigma = None self.ke...
2,174
42.5
113
py
transferlearning
transferlearning-master/code/DeepDA/loss_funcs/lmmd.py
from loss_funcs.mmd import MMDLoss from loss_funcs.adv import LambdaSheduler import torch import numpy as np class LMMDLoss(MMDLoss, LambdaSheduler): def __init__(self, num_class, kernel_type='rbf', kernel_mul=2.0, kernel_num=5, fix_sigma=None, gamma=1.0, max_iter=1000, **kwargs): ''' ...
3,835
40.695652
117
py
transferlearning
transferlearning-master/code/DeepDA/loss_funcs/daan.py
from loss_funcs.adv import * class DAANLoss(AdversarialLoss): def __init__(self, num_class, gamma=1.0, max_iter=1000, **kwargs): super(DAANLoss, self).__init__(gamma=gamma, max_iter=max_iter, **kwargs) self.num_class = num_class self.local_classifiers = torch.nn.ModuleList() for c i...
2,389
42.454545
93
py
transferlearning
transferlearning-master/code/DeepDA/loss_funcs/coral.py
import torch def CORAL(source, target, **kwargs): d = source.data.shape[1] ns, nt = source.data.shape[0], target.data.shape[0] # source covariance xm = torch.mean(source, 0, keepdim=True) - source xc = xm.t() @ xm / (ns - 1) # target covariance xmt = torch.mean(target, 0, keepdim=True) - ...
508
25.789474
55
py
transferlearning
transferlearning-master/code/feature_extractor/for_image_data/main.py
""" Extract features from pre-trained networks. The main procedures are finetune and extract features. Finetune: Given an Imagenet pretrained model (such as ResNet50), finetune it on a dataset (we call it source) Extractor: After fine-tune, extract features on the target domain using finetuned models on source This cl...
10,195
41.307054
129
py
transferlearning
transferlearning-master/code/feature_extractor/for_image_data/backbone.py
import numpy as np import torch import torch.nn as nn import torchvision from torchvision import models # convnet without the last layer class AlexNetFc(nn.Module): def __init__(self): super(AlexNetFc, self).__init__() model_alexnet = models.alexnet(pretrained=True) self.features = model_a...
5,961
29.418367
68
py
transferlearning
transferlearning-master/code/feature_extractor/for_image_data/models.py
import torch import torch.nn as nn import backbone class Network(nn.Module): def __init__(self, base_net='alexnet', n_class=31): super(Network, self).__init__() self.n_class = n_class self.base_network = backbone.network_dict[base_net]() self.classifier_layer = nn.Linear( ...
703
28.333333
61
py
transferlearning
transferlearning-master/code/feature_extractor/for_image_data/data_load.py
from torchvision import datasets, transforms import torch from PIL import Image # This file works for RGB images. def load_data(data_folder, batch_size, phase='train', train_val_split=True, train_ratio=.8): transform_dict = { 'train': transforms.Compose( [transforms.Resize(256), t...
5,161
44.280702
120
py
transferlearning
transferlearning-master/code/feature_extractor/for_digit_data/digit_data_loader.py
# encoding=utf-8 """ Created on 10:35 2018/12/29 @author: Jindong Wang """ import gzip import pickle from scipy.io import loadmat import torch.utils.data as data from PIL import Image import numpy as np import torchvision.transforms as transforms import torch ## For loading datasets of MNIST, USPS, and SVHN...
7,814
40.131579
105
py
transferlearning
transferlearning-master/code/feature_extractor/for_digit_data/digit_network.py
# encoding=utf-8 """ Created on 10:29 2018/12/29 @author: Jindong Wang """ import torch.nn as nn class Network(nn.Module): def __init__(self): super(Network, self).__init__() self.feature = nn.Sequential() self.feature.add_module('f_conv1', nn.Conv2d(3, 64, kernel_size=5)) ...
2,315
38.931034
77
py
transferlearning
transferlearning-master/code/feature_extractor/for_digit_data/digit_deep_feature.py
# encoding=utf-8 """ Created on 10:47 2018/12/29 @author: Jindong Wang """ from __future__ import print_function import argparse import data_loader import numpy as np import torch import torch.nn as nn import torch.optim as optim import torchvision import time import copy import digit_data_loader import dig...
6,201
41.190476
126
py
transferlearning
transferlearning-master/code/distance/coral_pytorch.py
# Compute CORAL loss using pytorch # Reference: DCORAL: Correlation Alignment for Deep Domain Adaptation, ECCV-16. import torch def CORAL_loss(source, target): d = source.data.shape[1] ns, nt = source.data.shape[0], target.data.shape[0] # source covariance xm = torch.mean(source, 0, keepdim=True) - so...
1,241
31.684211
79
py
transferlearning
transferlearning-master/code/distance/mmd_pytorch.py
# Compute MMD distance using pytorch import torch import torch.nn as nn class MMD_loss(nn.Module): def __init__(self, kernel_type='rbf', kernel_mul=2.0, kernel_num=5): super(MMD_loss, self).__init__() self.kernel_num = kernel_num self.kernel_mul = kernel_mul self.fix_sigma = None ...
2,200
40.528302
113
py
transferlearning
transferlearning-master/code/DeepDG/alg/opt.py
# coding=utf-8 import torch def get_params(alg, args, inner=False): if inner: params = [ {'params': alg[0].parameters(), 'lr': args.lr_decay1 * args.inner_lr}, {'params': alg[1].parameters(), 'lr': args.lr_decay2 * args.inner_lr}, {'params': al...
1,500
35.609756
99
py
transferlearning
transferlearning-master/code/DeepDG/alg/modelopera.py
# coding=utf-8 import torch from network import img_network def get_fea(args): if args.dataset == 'dg5': net = img_network.DTNBase() elif args.net.startswith('res'): net = img_network.ResBase(args.net) else: net = img_network.VGGBase(args.net) return net def accuracy(network,...
803
22.647059
67
py
transferlearning
transferlearning-master/code/DeepDG/alg/algs/base.py
# coding=utf-8 import torch class Algorithm(torch.nn.Module): def __init__(self, args): super(Algorithm, self).__init__() def update(self, minibatches, opt, sch): raise NotImplementedError def predict(self, x): raise NotImplementedError
278
17.6
44
py
transferlearning
transferlearning-master/code/DeepDG/alg/algs/MLDG.py
# coding=utf-8 import torch import copy import torch.nn.functional as F from alg.opt import * import torch.autograd as autograd from datautil.util import random_pairs_of_minibatches_by_domainperm from alg.algs.ERM import ERM class MLDG(ERM): def __init__(self, args): super(MLDG, self).__init__(args) ...
2,187
29.816901
89
py
transferlearning
transferlearning-master/code/DeepDG/alg/algs/MMD.py
# coding=utf-8 import torch import torch.nn.functional as F from alg.algs.ERM import ERM class MMD(ERM): def __init__(self, args): super(MMD, self).__init__(args) self.args = args self.kernel_type = "gaussian" def my_cdist(self, x1, x2): x1_norm = x1.pow(2).sum(dim=-1, keepdi...
2,043
29.969697
119
py
transferlearning
transferlearning-master/code/DeepDG/alg/algs/ERM.py
# coding=utf-8 import torch import torch.nn as nn import torch.nn.functional as F from alg.modelopera import get_fea from network import common_network from alg.algs.base import Algorithm class ERM(Algorithm): """ Empirical Risk Minimization (ERM) """ def __init__(self, args): super(ERM, sel...
1,189
28.02439
75
py
transferlearning
transferlearning-master/code/DeepDG/alg/algs/CORAL.py
# coding=utf-8 import torch import torch.nn.functional as F from alg.algs.ERM import ERM class CORAL(ERM): def __init__(self, args): super(CORAL, self).__init__(args) self.args = args self.kernel_type = "mean_cov" def coral(self, x, y): mean_x = x.mean(0, keepdim=True) ...
1,656
29.685185
121
py
transferlearning
transferlearning-master/code/DeepDG/alg/algs/RSC.py
# coding=utf-8 import numpy as np import torch import torch.nn.functional as F import torch.autograd as autograd from alg.algs.ERM import ERM class RSC(ERM): def __init__(self, args): super(RSC, self).__init__(args) self.drop_f = (1 - args.rsc_f_drop_factor) * 100 self.drop_b = (1 - args....
2,155
35.542373
75
py
transferlearning
transferlearning-master/code/DeepDG/alg/algs/Mixup.py
# coding=utf-8 import numpy as np import torch.nn.functional as F from datautil.util import random_pairs_of_minibatches from alg.algs.ERM import ERM class Mixup(ERM): def __init__(self, args): super(Mixup, self).__init__(args) self.args = args def update(self, minibatches, opt, sch): ...
986
26.416667
94
py
transferlearning
transferlearning-master/code/DeepDG/alg/algs/DANN.py
# coding=utf-8 import torch import torch.nn as nn import torch.nn.functional as F from alg.modelopera import get_fea from network import Adver_network, common_network from alg.algs.base import Algorithm class DANN(Algorithm): def __init__(self, args): super(DANN, self).__init__(args) self.feat...
1,890
34.018519
95
py
transferlearning
transferlearning-master/code/DeepDG/datautil/getdataloader.py
# coding=utf-8 import numpy as np import sklearn.model_selection as ms from torch.utils.data import DataLoader import datautil.imgdata.util as imgutil from datautil.imgdata.imgdataload import ImageDataset from datautil.mydataloader import InfiniteDataLoader def get_img_dataloader(args): rate = 0.2 trdatalist...
2,547
41.466667
131
py
transferlearning
transferlearning-master/code/DeepDG/datautil/util.py
# coding=utf-8 import numpy as np import torch def Nmax(test_envs, d): for i in range(len(test_envs)): if d < test_envs[i]: return i return len(test_envs) def random_pairs_of_minibatches_by_domainperm(minibatches): perm = torch.randperm(len(minibatches)).tolist() pairs = [] ...
1,912
36.509804
112
py
transferlearning
transferlearning-master/code/DeepDG/datautil/mydataloader.py
# coding=utf-8 import torch class _InfiniteSampler(torch.utils.data.Sampler): """Wraps another Sampler to yield an infinite stream.""" def __init__(self, sampler): self.sampler = sampler def __iter__(self): while True: for batch in self.sampler: yield batch ...
1,397
26.96
84
py
transferlearning
transferlearning-master/code/DeepDG/datautil/imgdata/util.py
# coding=utf-8 from torchvision import transforms from PIL import Image, ImageFile ImageFile.LOAD_TRUNCATED_IMAGES = True def image_train(dataset, resize_size=256, crop_size=224): if dataset == 'dg5': return transforms.Compose([ transforms.Resize(32), transforms.ToTensor(), ...
1,587
27.872727
66
py
transferlearning
transferlearning-master/code/DeepDG/datautil/imgdata/imgdataload.py
# coding=utf-8 from torch.utils.data import Dataset import numpy as np from datautil.util import Nmax from datautil.imgdata.util import rgb_loader, l_loader from torchvision.datasets import ImageFolder class ImageDataset(object): def __init__(self, dataset, task, root_dir, domain_name, domain_label=-1, labels=Non...
2,046
33.116667
170
py
transferlearning
transferlearning-master/code/DeepDG/network/Adver_network.py
import torch import torch.nn as nn from torch.autograd import Function class ReverseLayerF(Function): @staticmethod def forward(ctx, x, alpha): ctx.alpha = alpha return x.view_as(x) @staticmethod def backward(ctx, grad_output): output = grad_output.neg() * ctx.alpha re...
964
25.805556
69
py
transferlearning
transferlearning-master/code/DeepDG/network/img_network.py
# coding=utf-8 import torch.nn as nn from torchvision import models vgg_dict = {"vgg11": models.vgg11, "vgg13": models.vgg13, "vgg16": models.vgg16, "vgg19": models.vgg19, "vgg11bn": models.vgg11_bn, "vgg13bn": models.vgg13_bn, "vgg16bn": models.vgg16_bn, "vgg19bn": models.vgg19_bn} class VGGBase(nn.Modu...
3,295
31
149
py
transferlearning
transferlearning-master/code/DeepDG/network/util.py
# coding=utf-8 import torch.nn as nn import numpy as np def calc_coeff(iter_num, high=1.0, low=0.0, alpha=10.0, max_iter=10000.0): return np.float(2.0 * (high - low) / (1.0 + np.exp(-alpha*iter_num / max_iter)) - (high - low) + low) def init_weights(m): classname = m.__class__.__name__ if classname.find...
688
31.809524
105
py
transferlearning
transferlearning-master/code/DeepDG/network/common_network.py
# coding=utf-8 import torch.nn as nn from network.util import init_weights import torch.nn.utils.weight_norm as weightNorm class feat_bottleneck(nn.Module): def __init__(self, feature_dim, bottleneck_dim=256, type="ori"): super(feat_bottleneck, self).__init__() self.bn = nn.BatchNorm1d(bottleneck_...
1,675
30.037037
69
py
transferlearning
transferlearning-master/code/DeepDG/utils/util.py
# coding=utf-8 import random import numpy as np import torch import sys import os import torchvision import PIL def set_random_seed(seed=0): # seed setting random.seed(seed) np.random.seed(seed) torch.manual_seed(seed) torch.cuda.manual_seed(seed) torch.backends.cudnn.deterministic = True ...
3,946
29.361538
67
py
transferlearning
transferlearning-master/code/deep/finetune_AlexNet_ResNet/data_loader.py
from torchvision import datasets, transforms import torch import os def load_data(root_path, dir, batch_size, phase): transform_dict = { 'src': transforms.Compose( [transforms.RandomResizedCrop(224), transforms.RandomHorizontalFlip(), transforms.ToTensor(), transforms.No...
2,085
43.382979
127
py
transferlearning
transferlearning-master/code/deep/finetune_AlexNet_ResNet/finetune_office31.py
from __future__ import print_function import argparse import data_loader import numpy as np import torch import torch.nn as nn import torch.optim as optim import torchvision import time # Command setting parser = argparse.ArgumentParser(description='Finetune') parser.add_argument('--model', type=str, default='resne...
6,270
38.19375
121
py
transferlearning
transferlearning-master/code/deep/DANN(RevGrad)/adv_layer.py
import torch import torch.nn as nn from torch.autograd import Function import torch.nn.functional as F class ReverseLayerF(Function): @staticmethod def forward(ctx, x, alpha): ctx.alpha = alpha return x.view_as(x) @staticmethod def backward(ctx, grad_output): output = grad_ou...
860
25.090909
54
py
transferlearning
transferlearning-master/code/deep/TCP/mmd.py
import torch from functools import partial from torch.autograd import Variable # Consider linear time MMD with a linear kernel: # K(f(x), f(y)) = f(x)^Tf(y) # h(z_i, z_j) = k(x_i, x_j) + k(y_i, y_j) - k(x_i, y_j) - k(x_j, y_i) # = [f(x_i) - f(y_i)]^T[f(x_j) - f(y_j)] # # f_of_X: batch_size * k # f_of_Y: b...
3,688
34.471154
100
py
transferlearning
transferlearning-master/code/deep/TCP/dataset.py
import numpy as np import torch import torch.backends.cudnn as cudnn import torch.nn as nn import torch.nn.parallel import torch.optim as optim import torch.utils.data as data import torchvision.datasets as datasets import torchvision.models as models import torchvision.transforms as transforms from PIL import Image im...
1,701
36.822222
91
py
transferlearning
transferlearning-master/code/deep/TCP/prune.py
import torch from torch.autograd import Variable from torchvision import models import cv2 import sys import numpy as np from IPython import embed def replace_layers(model, i, indexes, layers): if i in indexes: return layers[indexes.index(i)] return model[i] def prune_vgg16_conv_layer(model, layer_ind...
4,891
37.519685
93
py
transferlearning
transferlearning-master/code/deep/TCP/tools.py
# -*- coding: utf-8 -*- import torch from IPython import embed import torchvision import torch.nn as nn from torch.autograd import Variable import torchvision.models as models import numpy as np def print_layers_num(): resnet = AlexNet.alexnet() def foo(net): childrens = list(net.children()) i...
4,919
29.37037
127
py
transferlearning
transferlearning-master/code/deep/TCP/finetune.py
from IPython import embed import torch from torch.autograd import Variable from torchvision import models import cv2 import sys import numpy as np import torchvision import torch.nn as nn import torch.nn.functional as F import torch.optim as optim import dataset from prune import * import argparse from operator import ...
16,921
40.577396
129
py
transferlearning
transferlearning-master/code/deep/DaNN/main.py
import DaNN import numpy as np import torch import torch.nn as nn import torch.optim as optim from tqdm import tqdm import data_loader import mmd DEVICE = torch.device('cuda' if torch.cuda.is_available() else 'cpu') LEARNING_RATE = 0.02 MOMEMTUN = 0.05 L2_WEIGHT = 0.003 DROPOUT = 0.5 N_EPOCH = 900 BATCH_SIZE = [64, 6...
4,151
34.487179
105
py
transferlearning
transferlearning-master/code/deep/DaNN/mmd.py
#!/usr/bin/env python # encoding: utf-8 import torch min_var_est = 1e-8 # Consider linear time MMD with a linear kernel: # K(f(x), f(y)) = f(x)^Tf(y) # h(z_i, z_j) = k(x_i, x_j) + k(y_i, y_j) - k(x_i, y_j) - k(x_j, y_i) # = [f(x_i) - f(y_i)]^T[f(x_j) - f(y_j)] # # f_of_X: batch_size * k # f_of_Y: batch...
6,773
37.708571
131
py
transferlearning
transferlearning-master/code/deep/DaNN/data_loader.py
import torchvision import torch from torchvision import datasets,transforms def load_data(root_dir,domain,batch_size): transform = transforms.Compose([ transforms.Grayscale(), transforms.Resize([28, 28]), transforms.ToTensor(), transforms.Normalize(mean=(0,),std=(1,)), ] ) ...
1,139
31.571429
130
py
transferlearning
transferlearning-master/code/deep/DaNN/DaNN.py
import torch.nn as nn class DaNN(nn.Module): def __init__(self, n_input=28 * 28, n_hidden=256, n_class=10): super(DaNN, self).__init__() self.layer_input = nn.Linear(n_input, n_hidden) self.dropout = nn.Dropout(p=0.5) self.relu = nn.ReLU() self.layer_hidden = nn.Linear(n_hi...
679
31.380952
66
py
transferlearning
transferlearning-master/code/deep/DeepMEDA/main.py
import torch import torch.nn.functional as F import math import pretty_errors import argparse import numpy as np from deep_meda import DeepMEDA import data_loader def load_data(root_path, src, tar, batch_size): kwargs = {'num_workers': 1, 'pin_memory': True} loader_src = data_loader.load_training(root_path, ...
6,090
38.810458
180
py
transferlearning
transferlearning-master/code/deep/DeepMEDA/ResNet.py
import torch.nn as nn import math import torch.utils.model_zoo as model_zoo __all__ = ['ResNet', 'resnet18', 'resnet34', 'resnet50', 'resnet101', 'resnet152'] model_urls = { 'resnet18': 'https://download.pytorch.org/models/resnet18-5c106cde.pth', 'resnet34': 'https://download.pytorch.org/models/re...
5,288
31.25
99
py
transferlearning
transferlearning-master/code/deep/DeepMEDA/mmd.py
import torch import torch.nn as nn from Weight import Weight class MMD_loss(nn.Module): def __init__(self, kernel_type='rbf', kernel_mul=2.0, kernel_num=5): super(MMD_loss, self).__init__() self.kernel_num = kernel_num self.kernel_mul = kernel_mul self.fix_sigma = None sel...
3,117
41.712329
113
py
transferlearning
transferlearning-master/code/deep/DeepMEDA/Weight.py
import numpy as np import torch def convert_to_onehot(sca_label, class_num=31): return np.eye(class_num)[sca_label] class Weight: @staticmethod def cal_weight(s_label, t_label, type='visual', batch_size=32, class_num=31): batch_size = s_label.size()[0] s_sca_label = s_label.cpu().data.nump...
2,119
38.259259
100
py
transferlearning
transferlearning-master/code/deep/DeepMEDA/data_loader.py
from torchvision import datasets, transforms import torch import os def load_training(root_path, dir, batch_size, kwargs): transform = transforms.Compose( [transforms.Resize([256, 256]), transforms.RandomCrop(224), transforms.RandomHorizontalFlip(), transforms.ToTensor()]) da...
915
42.619048
115
py
transferlearning
transferlearning-master/code/deep/DeepMEDA/deep_meda.py
import torch import torch.nn as nn import ResNet import mmd import dynamic_factor class DeepMEDA(nn.Module): def __init__(self, num_classes=31, bottle_neck=True): super(DeepMEDA, self).__init__() self.feature_layers = ResNet.resnet50(True) self.mmd_loss = mmd.MMD_loss() self.bottle...
1,434
35.794872
182
py
transferlearning
transferlearning-master/code/deep/DAAN/data_loader.py
from torchvision import datasets, transforms import torch import numpy as np from torchvision import transforms import os from PIL import Image, ImageOps class ResizeImage(): def __init__(self, size): if isinstance(size, int): self.size = (int(size), int(size)) else: self.size = size ...
1,751
31.444444
116
py
transferlearning
transferlearning-master/code/deep/DAAN/functions.py
from torch.autograd import Function class ReverseLayerF(Function): @staticmethod def forward(ctx, x, alpha): ctx.alpha = alpha return x.view_as(x) @staticmethod def backward(ctx, grad_output): output = grad_output.neg() * ctx.alpha return output, None
306
17.058824
46
py
transferlearning
transferlearning-master/code/deep/DAAN/train.py
from __future__ import print_function import argparse import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim from torch.autograd import Variable import math import data_loader from model import DAAN from torch.utils import model_zoo import numpy as np from IPython import embed im...
8,623
43
124
py
transferlearning
transferlearning-master/code/deep/DAAN/model/DAAN.py
import torch.nn as nn from torch.nn import init from torch.autograd import Variable from functions import ReverseLayerF from IPython import embed import torch import model.backbone as backbone class DAANNet(nn.Module): def __init__(self, num_classes=65, base_net='ResNet50'): super(DAANNet, self).__init__(...
3,293
41.230769
72
py
transferlearning
transferlearning-master/code/deep/DAAN/model/backbone.py
import numpy as np import torch import torch.nn as nn import torchvision from torchvision import models from torch.autograd import Variable # convnet without the last layer class AlexNetFc(nn.Module): def __init__(self): super(AlexNetFc, self).__init__() model_alexnet = models.alexnet(pretrained=T...
5,244
30.220238
88
py
transferlearning
transferlearning-master/code/deep/MRAN/ResNet.py
import torch.nn as nn import math import torch.utils.model_zoo as model_zoo import mmd import torch import torch.nn.functional as F import random __all__ = ['ResNet', 'resnet50'] model_urls = { 'resnet50': 'https://download.pytorch.org/models/resnet50-19c8e357.pth', } def conv3x3(in_planes, out_planes, stride...
9,159
33.43609
99
py
transferlearning
transferlearning-master/code/deep/MRAN/mmd.py
#!/usr/bin/env python # encoding: utf-8 import torch import numpy as np from torch.autograd import Variable min_var_est = 1e-8 def guassian_kernel(source, target, kernel_mul=2.0, kernel_num=5, fix_sigma=None): n_samples = int(source.size()[0])+int(target.size()[0]) total = torch.cat([source, target], dim=0) ...
1,965
41.73913
98
py
transferlearning
transferlearning-master/code/deep/MRAN/data_loader.py
from torchvision import datasets, transforms import torch def load_training(root_path, dir, batch_size, kwargs): transform = transforms.Compose( [transforms.Resize([256, 256]), transforms.RandomCrop(224), transforms.RandomHorizontalFlip(), transforms.ToTensor()]) data = datas...
879
43
115
py
transferlearning
transferlearning-master/code/deep/MRAN/MRAN.py
from __future__ import print_function import argparse import torch import torch.nn.functional as F import torch.optim as optim import os import math import data_loader import ResNet as models from torch.utils import model_zoo os.environ["CUDA_VISIBLE_DEVICES"] = "3" # Training settings parser = argparse.ArgumentParser...
6,287
45.235294
120
py
transferlearning
transferlearning-master/code/ASR/Adapter/e2e_asr_adaptertransformer.py
# Copyright 2019 Shigeki Karita # Apache 2.0 (http://www.apache.org/licenses/LICENSE-2.0) """Transformer speech recognition model (pytorch).""" from argparse import Namespace from distutils.util import strtobool import logging import math import numpy import torch from espnet.nets.pytorch_backend.e2e_asr_transfor...
42,203
40.09445
177
py
transferlearning
transferlearning-master/code/ASR/Adapter/balanced_sampler.py
import torch import torch.utils.data import random import collections import logging import numpy as np from torch.utils.data.sampler import BatchSampler, WeightedRandomSampler # https://github.com/khornlund/pytorch-balanced-sampler class BalancedBatchSampler(torch.utils.data.sampler.Sampler): ''' https://git...
2,255
39.285714
108
py
transferlearning
transferlearning-master/code/ASR/Adapter/utils.py
import torch import logging from espnet.asr.asr_utils import add_results_to_json import argparse import numpy as np import collections import json def load_head_from_pretrained_model(model, model_path): model_dict = torch.load(model_path, map_location=lambda storage, loc: storage) if "model" in model_dict.key...
11,166
36.599327
159
py
transferlearning
transferlearning-master/code/ASR/Adapter/data_load.py
from espnet.utils.training.batchfy import make_batchset from torch.utils.data import DataLoader from torch.nn.utils.rnn import pad_sequence import torch import os import json import kaldiio import random import logging import sentencepiece as spm from balanced_sampler import BalancedBatchSampler #cv mt cnh ky dv sl el ...
13,219
35.318681
113
py
transferlearning
transferlearning-master/code/ASR/Adapter/train.py
import logging import os import collections from espnet.bin.asr_train import get_parser from espnet.utils.dynamic_import import dynamic_import from espnet.utils.deterministic_utils import set_deterministic_pytorch from espnet.asr.pytorch_backend.asr_init import freeze_modules from torch.nn.parallel import data_paralle...
25,561
46.779439
144
py
transferlearning
transferlearning-master/code/ASR/CMatch/distances.py
import torch def CORAL(source, target): DEVICE = source.device d = source.size(1) ns, nt = source.size(0), target.size(0) # source covariance tmp_s = torch.ones((1, ns)).to(DEVICE) @ source cs = (source.t() @ source - (tmp_s.t() @ tmp_s) / ns) / (ns - 1) # target covariance tmp_t = to...
2,668
38.835821
113
py
transferlearning
transferlearning-master/code/ASR/CMatch/utils.py
import torch import logging from espnet.asr.asr_utils import add_results_to_json import argparse import numpy as np import collections import json def str2bool(str): return True if str.lower() == 'true' else False def setup_logging(verbose=1): if verbose > 0: logging.basicConfig( level=lo...
10,126
36.64684
159
py
transferlearning
transferlearning-master/code/ASR/CMatch/ctc_aligner.py
import torch import numpy as np ''' Borrowed and modified from neural_sp: https://github.com/hirofumi0810/neural_sp/blob/154d9248b54e3888797fd81f93adc4700a75509a/neural_sp/models/seq2seq/decoders/ctc.py#L625 ''' LOG_0 = -1e10 LOG_1 = 0 def np2tensor(array, device=None): """Convert form np.ndarray to torch.Tens...
11,037
39.432234
134
py
transferlearning
transferlearning-master/code/ASR/CMatch/e2e_asr_udatransformer.py
import collections from espnet.nets.pytorch_backend.e2e_asr_transformer import * from espnet.nets.pytorch_backend.e2e_asr_transformer import E2E as SpeechTransformer from espnet.nets.pytorch_backend.transformer.encoder import * from espnet.nets.pytorch_backend.transformer.decoder import * from espnet.nets.pytorch_backe...
31,468
43.827635
154
py
transferlearning
transferlearning-master/code/ASR/CMatch/data_load.py
from espnet.utils.training.batchfy import make_batchset from torch.utils.data import DataLoader from torch.nn.utils.rnn import pad_sequence import torch import os import json import kaldiio import random import logging import sentencepiece as spm data_config = { "librispeech": { "train": "dump/train_960/d...
12,664
41.216667
134
py
transferlearning
transferlearning-master/code/ASR/CMatch/train.py
import logging import os import collections from espnet.bin.asr_train import get_parser from espnet.utils.dynamic_import import dynamic_import from espnet.utils.deterministic_utils import set_deterministic_pytorch from espnet.asr.pytorch_backend.asr_init import freeze_modules from torch.nn.parallel import data_paralle...
19,068
46.083951
320
py