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 |
|---|---|---|---|---|---|---|
UDAStrongBaseline | UDAStrongBaseline-master/UDAsbs/layers/sync_bn/unittest.py | # -*- coding: utf-8 -*-
# File : unittest.py
# Author : Jiayuan Mao
# Email : maojiayuan@gmail.com
# Date : 27/01/2018
#
# This file is part of Synchronized-BatchNorm-PyTorch.
# https://github.com/vacancy/Synchronized-BatchNorm-PyTorch
# Distributed under MIT License.
import unittest
import torch
class TorchTes... | 746 | 23.9 | 59 | py |
UDAStrongBaseline | UDAStrongBaseline-master/UDAsbs/layers/sync_bn/batchnorm.py | # -*- coding: utf-8 -*-
# File : batchnorm.py
# Author : Jiayuan Mao
# Email : maojiayuan@gmail.com
# Date : 27/01/2018
#
# This file is part of Synchronized-BatchNorm-PyTorch.
# https://github.com/vacancy/Synchronized-BatchNorm-PyTorch
# Distributed under MIT License.
import collections
import contextlib
import... | 15,978 | 39.35101 | 116 | py |
UDAStrongBaseline | UDAStrongBaseline-master/UDAsbs/layers/sync_bn/batchnorm_reimpl.py | #! /usr/bin/env python3
# -*- coding: utf-8 -*-
# File : batchnorm_reimpl.py
# Author : acgtyrant
# Date : 11/01/2018
#
# This file is part of Synchronized-BatchNorm-PyTorch.
# https://github.com/vacancy/Synchronized-BatchNorm-PyTorch
# Distributed under MIT License.
import torch
import torch.nn as nn
import torch... | 2,385 | 30.813333 | 95 | py |
UDAStrongBaseline | UDAStrongBaseline-master/UDAsbs/feature_extraction/cnn.py | from __future__ import absolute_import
from collections import OrderedDict
from ..utils import to_torch
def extract_cnn_feature(model, inputs, modules=None):
model.eval()
# with torch.no_grad():
inputs = to_torch(inputs).cuda()
if modules is None:
outputs = model(inputs)
outputs = ou... | 705 | 25.148148 | 56 | py |
UDAStrongBaseline | UDAStrongBaseline-master/UDAsbs/feature_extraction/database.py | from __future__ import absolute_import
import h5py
import numpy as np
from torch.utils.data import Dataset
class FeatureDatabase(Dataset):
def __init__(self, *args, **kwargs):
super(FeatureDatabase, self).__init__()
self.fid = h5py.File(*args, **kwargs)
def __enter__(self):
return se... | 1,311 | 24.230769 | 59 | py |
UDAStrongBaseline | UDAStrongBaseline-master/UDAsbs/loss/invariance.py | import torch
import torch.nn.functional as F
from torch import nn, autograd
from torch.autograd import Variable, Function
import numpy as np
import math
import warnings
warnings.filterwarnings("ignore")
class ExemplarMemory(Function):
def __init__(self, em, alpha=0.01):
super(ExemplarMemory, self).__init_... | 2,793 | 31.870588 | 94 | py |
UDAStrongBaseline | UDAStrongBaseline-master/UDAsbs/loss/triplet.py | from __future__ import absolute_import
import torch
from torch import nn
import torch.nn.functional as F
def euclidean_dist(x, y):
m, n = x.size(0), y.size(0)
xx = torch.pow(x, 2).sum(1, keepdim=True).expand(m, n)
yy = torch.pow(y, 2).sum(1, keepdim=True).expand(n, m).t()
dist = xx + yy
dist.addm... | 7,326 | 39.038251 | 160 | py |
UDAStrongBaseline | UDAStrongBaseline-master/UDAsbs/loss/crossentropy.py | import torch
import torch.nn as nn
import torch.nn.functional as F
class CrossEntropyLabelSmooth(nn.Module):
def __init__(self, num_classes, epsilon=0.1, reduce=True):
super(CrossEntropyLabelSmooth, self).__init__()
self.num_classes = num_classes
self.epsilon = epsilon
self.logsoftmax = nn.LogSoftmax(dim=1... | 1,162 | 28.075 | 82 | py |
UDAStrongBaseline | UDAStrongBaseline-master/UDAsbs/loss/multisoftmax.py | import torch
from torch import nn
import torch.nn.functional as F
eps = 1e-7
class NCECriterion(nn.Module):
"""
Eq. (12): L_{memorybank}
"""
def __init__(self, n_data):
super(NCECriterion, self).__init__()
self.n_data = n_data
def forward(self, x):
bsz = x.shape[0]
... | 3,800 | 29.166667 | 108 | py |
UDAStrongBaseline | UDAStrongBaseline-master/UDAsbs/metric_learning/distance.py | from __future__ import absolute_import
from __future__ import print_function
from __future__ import division
import numpy as np
import torch
from torch.nn import functional as F
def compute_distance_matrix(input1, input2, metric='euclidean'):
"""A wrapper function for computing distance matrix.
Args:
... | 2,454 | 31.733333 | 86 | py |
UDAStrongBaseline | UDAStrongBaseline-master/UDAsbs/utils/lr_scheduler.py | # encoding: utf-8
"""
@author: liaoxingyu
@contact: sherlockliao01@gmail.com
"""
from bisect import bisect_right
import torch
from torch.optim.lr_scheduler import *
# separating MultiStepLR with WarmupLR
# but the current LRScheduler design doesn't allow it
class WarmupMultiStepLR(torch.optim.lr_scheduler._LRSched... | 1,807 | 30.172414 | 80 | py |
UDAStrongBaseline | UDAStrongBaseline-master/UDAsbs/utils/loss_and_miner_utils.py | import torch
import numpy as np
import math
from . import common_functions as c_f
def logsumexp(x, keep_mask=None, add_one=True, dim=1):
max_vals, _ = torch.max(x, dim=dim, keepdim=True)
inside_exp = x - max_vals
exp = torch.exp(inside_exp)
if keep_mask is not None:
exp = exp*keep_mask
ins... | 7,816 | 34.694064 | 114 | py |
UDAStrongBaseline | UDAStrongBaseline-master/UDAsbs/utils/common_functions.py | import collections
import torch
from torch.autograd import Variable
import numpy as np
import os
import logging
import glob
import scipy.stats
import re
NUMPY_RANDOM = np.random
class Identity(torch.nn.Module):
def __init__(self):
super().__init__()
def forward(self, x):
return x
def try_n... | 9,084 | 28.306452 | 113 | py |
UDAStrongBaseline | UDAStrongBaseline-master/UDAsbs/utils/faiss_rerank.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
CVPR2017 paper:Zhong Z, Zheng L, Cao D, et al. Re-ranking Person Re-identification with k-reciprocal Encoding[J]. 2017.
url:http://openaccess.thecvf.com/content_cvpr_2017/papers/Zhong_Re-Ranking_Person_Re-Identification_CVPR_2017_paper.pdf
Matlab version: https://githu... | 4,838 | 38.663934 | 126 | py |
UDAStrongBaseline | UDAStrongBaseline-master/UDAsbs/utils/faiss_utils.py | import os
import numpy as np
import faiss
import torch
def swig_ptr_from_FloatTensor(x):
assert x.is_contiguous()
assert x.dtype == torch.float32
return faiss.cast_integer_to_float_ptr(
x.storage().data_ptr() + x.storage_offset() * 4)
def swig_ptr_from_LongTensor(x):
assert x.is_contiguous()
... | 3,182 | 28.201835 | 92 | py |
UDAStrongBaseline | UDAStrongBaseline-master/UDAsbs/utils/__init__.py | from __future__ import absolute_import
import torch
def to_numpy(tensor):
if torch.is_tensor(tensor):
return tensor.cpu().numpy()
elif type(tensor).__module__ != 'numpy':
raise ValueError("Cannot convert {} to numpy array"
.format(type(tensor)))
return tensor
de... | 594 | 26.045455 | 60 | py |
UDAStrongBaseline | UDAStrongBaseline-master/UDAsbs/utils/rerank.py | #!/usr/bin/env python2/python3
# -*- coding: utf-8 -*-
"""
Source: https://github.com/zhunzhong07/person-re-ranking
Created on Mon Jun 26 14:46:56 2017
@author: luohao
Modified by Yixiao Ge, 2020-3-14.
CVPR2017 paper:Zhong Z, Zheng L, Cao D, et al. Re-ranking Person Re-identification with k-reciprocal Encoding[J]. 2017... | 8,856 | 41.37799 | 119 | py |
UDAStrongBaseline | UDAStrongBaseline-master/UDAsbs/utils/serialization.py | from __future__ import print_function, absolute_import
import json
import os.path as osp
import shutil
import torch
from torch.nn import Parameter
from .osutils import mkdir_if_missing
def read_json(fpath):
with open(fpath, 'r') as f:
obj = json.load(f)
return obj
def write_json(obj, fpath):
m... | 1,758 | 27.370968 | 78 | py |
UDAStrongBaseline | UDAStrongBaseline-master/UDAsbs/utils/data/sampler.py | from __future__ import absolute_import
from collections import defaultdict
import math
import numpy as np
import copy
import random
import torch
from torch.utils.data.sampler import (
Sampler, SequentialSampler, RandomSampler, SubsetRandomSampler,
WeightedRandomSampler)
def No_index(a, b):
assert isinsta... | 3,547 | 32.471698 | 108 | py |
UDAStrongBaseline | UDAStrongBaseline-master/UDAsbs/utils/data/transformer.py | from __future__ import absolute_import
from torchvision.transforms import *
from PIL import Image
import random
import math
import numpy as np
class RectScale(object):
def __init__(self, height, width, interpolation=Image.BILINEAR):
self.height = height
self.width = width
self.interpolatio... | 3,358 | 33.989583 | 96 | py |
UDAStrongBaseline | UDAStrongBaseline-master/UDAsbs/utils/data/preprocessor.py | from __future__ import absolute_import
import os
import os.path as osp
from torch.utils.data import DataLoader, Dataset
import numpy as np
import random
import math
import torch
from PIL import Image
class Preprocessor(Dataset):
def __init__(self, dataset, root=None, transform=None, mutual=False):
super(Pr... | 4,805 | 30.827815 | 111 | py |
UDAStrongBaseline | UDAStrongBaseline-master/UDAsbs/utils/data/functional_our.py | # encoding: utf-8
"""
@author: liaoxingyu
@contact: sherlockliao01@gmail.com
"""
import numpy as np
import torch
from PIL import Image, ImageOps, ImageEnhance
def to_tensor(pic):
"""Convert a ``PIL Image`` or ``numpy.ndarray`` to tensor.
See ``ToTensor`` for more details.
Args:
pic (PIL Image ... | 5,912 | 30.121053 | 79 | py |
UDAStrongBaseline | UDAStrongBaseline-master/UDAsbs/utils/data/transforms.py | from __future__ import absolute_import
__all__ = ['ToTensor', 'RandomErasing', 'RandomPatch', 'AugMix', 'ColorChange', ]
from torchvision.transforms import *
from PIL import Image
import random
import math
import numpy as np
import cv2
from collections import deque
from .functional_our import to_tensor, augmentation... | 10,430 | 35.344948 | 96 | py |
UDAStrongBaseline | UDAStrongBaseline-master/UDAsbs/evaluation_metrics/classification.py | from __future__ import absolute_import
import torch
from ..utils import to_torch
def accuracy(output, target, topk=(1,)):
with torch.no_grad():
output, target = to_torch(output), to_torch(target)
maxk = max(topk)
batch_size = target.size(0)
_, pred = output.topk(maxk, 1, True, Tr... | 604 | 26.5 | 77 | py |
GraB | GraB-main/setup.py | import setuptools
with open("README.md", "r", encoding="utf-8") as fh:
long_description = fh.read()
setuptools.setup(
name="orderedsampler",
version="0.0.1",
author="Yucheng Lu",
author_email="yl2967@cornell.edu",
description="pytorch-based OrderedSampler that supports example ordering",
l... | 838 | 31.269231 | 78 | py |
GraB | GraB-main/neurips22/examples/nlp/BertGlue/train_bert_glue.py | # coding=utf-8
# Copyright 2021 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.apache.org/licenses/LICENSE-2.0
#
# Unless r... | 26,114 | 42.236755 | 127 | py |
GraB | GraB-main/neurips22/examples/nlp/word_language_model/main.py | # coding: utf-8
import argparse
import math
import os
import torch
import torch.nn as nn
import data
import model
import random
import tqdm
import time
from contextlib import contextmanager
from tensorboardX import SummaryWriter
from constants import _STALE_GRAD_SORT_, \
_RANDOM_RESHUFFLING_, \
... | 17,784 | 39.237557 | 125 | py |
GraB | GraB-main/neurips22/examples/nlp/word_language_model/generate.py | ###############################################################################
# Language Modeling on Wikitext-2
#
# This file generates new sentences sampled from the language model
#
###############################################################################
import argparse
import torch
import data
parser = ... | 3,080 | 38 | 89 | py |
GraB | GraB-main/neurips22/examples/nlp/word_language_model/model.py | import math
import torch
import torch.nn as nn
import torch.nn.functional as F
class RNNModel(nn.Module):
"""Container module with an encoder, a recurrent module, and a decoder."""
def __init__(self, rnn_type, ntoken, ninp, nhid, nlayers, dropout=0.5, tie_weights=False):
super(RNNModel, self).__init__... | 6,353 | 41.07947 | 110 | py |
GraB | GraB-main/neurips22/examples/nlp/word_language_model/data.py | import os
from io import open
import torch
class Dictionary(object):
def __init__(self):
self.word2idx = {}
self.idx2word = []
def add_word(self, word):
if word not in self.word2idx:
self.idx2word.append(word)
self.word2idx[word] = len(self.idx2word) - 1
... | 1,449 | 28.591837 | 65 | py |
GraB | GraB-main/neurips22/examples/vision/utils.py | import os
import torch
import time
import copy
import pickle
import logging
import lmdb
from contextlib import contextmanager
from io import StringIO
from constants import _STALE_GRAD_SORT_, \
_FRESH_GRAD_SORT_, \
_DM_SORT_, \
_MNIST_, \
_F... | 13,812 | 34.058376 | 113 | py |
GraB | GraB-main/neurips22/examples/vision/visionmodel.py | import torch
from constants import _MNIST_, _SQUEEZENET_
def accuracy(output, target, topk=(1,)):
"""Computes the precision@k for the specified values of k"""
maxk = max(topk)
batch_size = target.size(0)
_, pred = output.topk(maxk, 1, True, True)
pred = pred.t()
correct = pred.eq(target.view(1... | 1,312 | 26.93617 | 64 | py |
GraB | GraB-main/neurips22/examples/vision/train_logreg_mnist.py | import os
import random
import torch
import logging
import torchvision
import torchvision.datasets as datasets
from tensorboardX import SummaryWriter
import torchvision.transforms as transforms
from visionmodel import VisionModel
from arguments import get_args
from utils import train, validate, Timer, build_task_name
f... | 6,925 | 41.231707 | 146 | py |
GraB | GraB-main/neurips22/examples/vision/train_lenet_cifar.py | import os
import random
import torch
import logging
import torchvision
import torchvision.datasets as datasets
from tensorboardX import SummaryWriter
import torchvision.transforms as transforms
from visionmodel import VisionModel
from arguments import get_args
from utils import train, validate, Timer, build_task_name
f... | 7,986 | 41.71123 | 146 | py |
GraB | GraB-main/neurips22/examples/vision/models/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,001 | 30.459119 | 120 | py |
GraB | GraB-main/neurips22/examples/vision/models/lenet.py | # -*- coding: utf-8 -*-
from collections import OrderedDict
import torch.nn as nn
__all__ = ["lenet"]
class LeNet(nn.Module):
"""
Input - 3x32x32
C1 - 6@28x28 (5x5 kernel)
tanh
S2 - 6@14x14 (2x2 kernel, stride 2) Subsampling
C3 - 16@10x10 (5x5 kernel)
tanh
S4 - 16@5x5 (2x2 kernel, st... | 2,480 | 25.677419 | 83 | py |
GraB | GraB-main/neurips22/src/dmsort/algo.py | import torch
import copy
import random
from sklearn import random_projection
from .utils import flatten_grad
class Sort:
def sort(self, orders):
raise NotImplementedError
class StaleGradGreedySort(Sort):
"""
Implementation of the algorithm that greedily sort the examples using staled gradients,
... | 6,539 | 38.39759 | 113 | py |
GraB | GraB-main/neurips22/src/dmsort/utils.py | import torch
from sklearn import random_projection
def random_proj(data):
rp = random_projection.SparseRandomProjection(random_state=1)
return torch.from_numpy(rp.fit_transform(data))
def compute_avg_grad_error(args,
model,
train_batches,
... | 1,844 | 33.166667 | 91 | py |
GraB | GraB-main/examples/train_logistic_regression.py | import random
import torch
import torchvision
from torch.nn import CrossEntropyLoss, Linear
from orderedsampler import OrderedSampler
from tensorboardX import SummaryWriter
def accuracy(output, target, topk=(1,)):
"""Computes the precision@k for the specified values of k"""
maxk = max(topk)
batch_size = ta... | 4,204 | 31.346154 | 121 | py |
GraB | GraB-main/src/orderedsampler/__init__.py | from absl import logging
from collections import OrderedDict
from typing import List, Union, Sized, Tuple, Dict
import torch
from torch.nn import Module
from torch.utils.data import IterableDataset
from torch.utils.data.sampler import Sampler
from backpack import extend, backpack
from backpack.extensions import Batch... | 10,988 | 50.834906 | 125 | py |
GraB | GraB-main/src/orderedsampler/sorter/meanbalance.py | import torch
from .sorterbase import Sort
from typing import List, Dict
from torch.nn import Module
class MeanBalance(Sort):
r"""Implement Gradient Balancing using stale mean.
More details can be found in: https://arxiv.org/abs/2205.10733.
Args:
prob_balance (bool): If ``True``, the balancing will... | 4,637 | 40.410714 | 96 | py |
GraB | GraB-main/src/orderedsampler/sorter/utils.py | import torch
from torch import Tensor
from torch.nn import Module
from torch._utils import _flatten_dense_tensors
from typing import Tuple
from collections import OrderedDict
def flatten_batch_grads(model: Module) -> Tensor:
all_grads = []
for param in model.parameters():
if param.grad is not None:
... | 771 | 28.692308 | 78 | py |
GraB | GraB-main/src/orderedsampler/sorter/pairbalance.py | import torch
from .sorterbase import Sort
from typing import List, Dict
from torch.nn import Module
class PairBalance(Sort):
r"""Implement Pair Balance algorithm.
For a given sequence z_i, i = 1, 2, ..., n, we balance z_{2t} - z_{2t-1}.
This avoids using the stale mean as in MeanBalance, and can b... | 7,142 | 43.924528 | 94 | py |
GraB | GraB-main/src/orderedsampler/sorter/subroutine.py | import random
import torch
from torch import Tensor
def deterministic_balance(vec: Tensor, aggregator: Tensor):
if torch.norm(aggregator + vec) <= torch.norm(aggregator - vec):
return 1
else:
return -1
def probabilistic_balance(vec, aggregator):
p = 0.5 - torch.dot(vec, aggregator) / 60
... | 395 | 18.8 | 68 | py |
vadesc | vadesc-main/main.py | """
Runs the VaDeSC model.
"""
import argparse
from pathlib import Path
import yaml
import logging
import tensorflow as tf
import tensorflow_probability as tfp
import os
from models.losses import Losses
from train import run_experiment
tfd = tfp.distributions
tfkl = tf.keras.layers
tfpl = tfp.layers
tfk = tf.keras
#... | 5,142 | 37.380597 | 112 | py |
vadesc | vadesc-main/train.py | import time
from pathlib import Path
import tensorflow as tf
import tensorflow_probability as tfp
import numpy as np
from sklearn.mixture import GaussianMixture
from sklearn.cluster import KMeans
from sklearn.metrics.cluster import normalized_mutual_info_score, adjusted_rand_score
import uuid
import math
from utils.eva... | 16,068 | 46.54142 | 166 | py |
vadesc | vadesc-main/models/losses.py | """
Loss functions for the reconstruction term of the ELBO.
"""
import tensorflow as tf
class Losses:
def __init__(self, configs):
self.input_dim = configs['training']['inp_shape']
self.tuple = False
if isinstance(self.input_dim, list):
print("\nData is tuple!\n")
s... | 1,721 | 43.153846 | 120 | py |
vadesc | vadesc-main/models/model.py | """
VaDeSC model.
"""
import tensorflow as tf
import tensorflow_probability as tfp
import os
from models.networks import (VGGEncoder, VGGDecoder, Encoder, Decoder, Encoder_small, Decoder_small)
from utils.utils import weibull_scale, weibull_log_pdf, tensor_slice
# Pretrain autoencoder
checkpoint_path = "autoencoder/... | 9,434 | 48.657895 | 124 | py |
vadesc | vadesc-main/models/networks.py | """
Encoder and decoder architectures used by VaDeSC.
"""
import tensorflow as tf
import tensorflow_probability as tfp
from tensorflow.keras import layers
tfd = tfp.distributions
tfkl = tf.keras.layers
tfpl = tfp.layers
tfk = tf.keras
# Wide MLP encoder and decoder architectures
class Encoder(layers.Layer):
def... | 5,648 | 32.229412 | 119 | py |
vadesc | vadesc-main/datasets/survivalMNIST/survivalMNIST_data.py | """
Survival MNIST dataset.
Based on Pölsterl's tutorial:
https://k-d-w.org/blog/2019/07/survival-analysis-for-deep-learning/
https://github.com/sebp/survival-cnn-estimator
"""
import numpy as np
from numpy.random import choice, uniform, normal
import tensorflow as tf
import tensorflow.keras.datasets.mnist as ... | 4,151 | 34.487179 | 122 | py |
vadesc | vadesc-main/utils/utils.py | """
miscellaneous utility functions.
"""
import matplotlib
import matplotlib.pyplot as plt
import logging
from sklearn.utils.linear_assignment_ import linear_assignment
import numpy as np
from scipy.stats import weibull_min, fisk
import sys
from utils.constants import ROOT_LOGGER_STR
import tensorflow as tf
impor... | 5,806 | 34.408537 | 133 | py |
vadesc | vadesc-main/utils/data_utils.py | """
Utility functions for data loading.
"""
import tensorflow as tf
import tensorflow_probability as tfp
import numpy as np
from sklearn.model_selection import train_test_split
import pandas as pd
from sklearn.preprocessing import StandardScaler
from tensorflow.keras.utils import to_categorical
from datasets.survivalM... | 14,038 | 54.710317 | 150 | py |
vadesc | vadesc-main/posthoc_explanations/explainer_utils.py | import pandas as pd
import numpy as np
from sklearn.preprocessing import MinMaxScaler, StandardScaler
import keras
import math
import seaborn as sns
import matplotlib.pyplot as plt
import matplotlib
############### PROTOTYPES SAMPLING UTILITY FUNCTIONS #####################################
def Prototypes_sampler... | 7,993 | 32.033058 | 158 | py |
sdmgrad | sdmgrad-main/toy/toy.py | from copy import deepcopy
from mpl_toolkits.mplot3d import Axes3D
from matplotlib import cm, ticker
from matplotlib.colors import LogNorm
from tqdm import tqdm
from scipy.optimize import minimize, Bounds, minimize_scalar
import matplotlib.pyplot as plt
import numpy as np
import time
import torch
import torch.nn as nn
... | 13,100 | 28.308725 | 110 | py |
sdmgrad | sdmgrad-main/mtrl/mtrl_files/sdmgrad.py | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
from copy import deepcopy
from typing import Iterable, List, Optional, Tuple
import numpy as np
import time
import torch
from omegaconf import OmegaConf
from mtrl.agent import grad_manipulation as grad_manipulation_agent
from mtrl.utils.types impo... | 11,791 | 35.965517 | 163 | py |
sdmgrad | sdmgrad-main/nyuv2/model_segnet_single.py | import torch.nn as nn
import torch.optim as optim
import torch.nn.functional as F
import argparse
from create_dataset import *
from utils import *
parser = argparse.ArgumentParser(description='Single-task: One Task')
parser.add_argument('--task', default='semantic', type=str, help='choose task: semantic, depth, norma... | 6,820 | 43.292208 | 120 | py |
sdmgrad | sdmgrad-main/nyuv2/evaluate.py | import matplotlib
import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np
import torch
import itertools
methods = [
"sdmgrad-1e-1", "sdmgrad-2e-1", "sdmgrad-3e-1", "sdmgrad-4e-1", "sdmgrad-5e-1", "sdmgrad-6e-1", "sdmgrad-7e-1",
"sdmgrad-8e-1", "sdmgrad-9e-1", "sdmgrad-1e0"
]
colors = ["C0", "... | 3,777 | 30.747899 | 117 | py |
sdmgrad | sdmgrad-main/nyuv2/model_segnet_stan.py | import torch.nn as nn
import torch.optim as optim
import torch.nn.functional as F
import argparse
from create_dataset import *
from utils import *
parser = argparse.ArgumentParser(description='Single-task: Attention Network')
parser.add_argument('--task', default='semantic', type=str, help='choose task: semantic, dep... | 11,017 | 49.310502 | 119 | py |
sdmgrad | sdmgrad-main/nyuv2/utils.py | import numpy as np
import time
import torch
import torch.nn.functional as F
from copy import deepcopy
from min_norm_solvers import MinNormSolver
from scipy.optimize import minimize, Bounds, minimize_scalar
def euclidean_proj_simplex(v, s=1):
""" Compute the Euclidean projection on a positive simplex
Solves t... | 31,500 | 43.242978 | 130 | py |
sdmgrad | sdmgrad-main/nyuv2/model_segnet_split.py | import torch.nn as nn
import torch.optim as optim
import torch.nn.functional as F
import argparse
import torch.utils.data.sampler as sampler
from create_dataset import *
from utils import *
parser = argparse.ArgumentParser(description='Multi-task: Split')
parser.add_argument('--type', default='standard', type=str, he... | 7,942 | 44.649425 | 119 | py |
sdmgrad | sdmgrad-main/nyuv2/min_norm_solvers.py | # This code is from
# Multi-Task Learning as Multi-Objective Optimization
# Ozan Sener, Vladlen Koltun
# Neural Information Processing Systems (NeurIPS) 2018
# https://github.com/intel-isl/MultiObjectiveOptimization
import numpy as np
import torch
class MinNormSolver:
MAX_ITER = 20
STOP_CRIT = 1e-5
def ... | 7,358 | 35.979899 | 147 | py |
sdmgrad | sdmgrad-main/nyuv2/model_segnet_mtan.py | import numpy as np
import random
import torch.nn as nn
import torch.optim as optim
import torch.nn.functional as F
import argparse
import torch.utils.data.sampler as sampler
from create_dataset import *
from utils import *
parser = argparse.ArgumentParser(description='Multi-task: Attention Network')
parser.add_argume... | 11,617 | 49.077586 | 119 | py |
sdmgrad | sdmgrad-main/nyuv2/create_dataset.py | from torch.utils.data.dataset import Dataset
import os
import torch
import torch.nn.functional as F
import fnmatch
import numpy as np
import random
class RandomScaleCrop(object):
"""
Credit to Jialong Wu from https://github.com/lorenmt/mtan/issues/34.
"""
def __init__(self, scale=[1.0, 1.2, 1.5]):
... | 3,568 | 40.988235 | 127 | py |
sdmgrad | sdmgrad-main/nyuv2/model_segnet_cross.py | import numpy as np
import random
import torch.nn as nn
import torch.optim as optim
import torch.nn.functional as F
import argparse
import torch.utils.data.sampler as sampler
from create_dataset import *
from utils import *
parser = argparse.ArgumentParser(description='Multi-task: Cross')
parser.add_argument('--weight... | 9,335 | 47.879581 | 119 | py |
sdmgrad | sdmgrad-main/nyuv2/model_segnet_mt.py | import numpy as np
import random
import torch.nn as nn
import torch.optim as optim
import torch.nn.functional as F
import argparse
import torch.utils.data.sampler as sampler
from create_dataset import *
from utils import *
parser = argparse.ArgumentParser(description='Multi-task: Split')
parser.add_argument('--type',... | 18,041 | 48.027174 | 119 | py |
sdmgrad | sdmgrad-main/consistency/model_resnet.py | # resnet18 base model for Pareto MTL
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.nn.modules.loss import CrossEntropyLoss
from torchvision import models
class RegressionTrainResNet(torch.nn.Module):
def __init__(self, model, init_weight):
super(RegressionTrainResNet, sel... | 2,346 | 31.150685 | 80 | py |
sdmgrad | sdmgrad-main/consistency/utils.py | import numpy as np
from min_norm_solvers import MinNormSolver
from scipy.optimize import minimize, Bounds, minimize_scalar
import torch
from torch import linalg as LA
from torch.nn import functional as F
def euclidean_proj_simplex(v, s=1):
""" Compute the Euclidean projection on a positive simplex
Solves the... | 5,435 | 34.070968 | 113 | py |
sdmgrad | sdmgrad-main/consistency/model_lenet.py | # lenet base model for Pareto MTL
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.nn.modules.loss import CrossEntropyLoss
class RegressionTrain(torch.nn.Module):
def __init__(self, model, init_weight):
super(RegressionTrain, self).__init__()
self.model = model
... | 2,006 | 26.875 | 80 | py |
sdmgrad | sdmgrad-main/consistency/min_norm_solvers.py | # This code is from
# Multi-Task Learning as Multi-Objective Optimization
# Ozan Sener, Vladlen Koltun
# Neural Information Processing Systems (NeurIPS) 2018
# https://github.com/intel-isl/MultiObjectiveOptimization
import numpy as np
import torch
class MinNormSolver:
MAX_ITER = 20
STOP_CRIT = 1e-5
def ... | 7,364 | 36.01005 | 147 | py |
sdmgrad | sdmgrad-main/consistency/train.py | import numpy as np
import torch
import torch.utils.data
from torch import linalg as LA
from torch.autograd import Variable
from model_lenet import RegressionModel, RegressionTrain
from model_resnet import MnistResNet, RegressionTrainResNet
from utils import *
import pickle
import argparse
parser = argparse.Argument... | 7,010 | 36.292553 | 118 | py |
sdmgrad | sdmgrad-main/cityscapes/model_segnet_single.py | import torch.nn as nn
import torch.optim as optim
import torch.nn.functional as F
import argparse
from create_dataset import *
from utils import *
parser = argparse.ArgumentParser(description='Single-task: One Task')
parser.add_argument('--task', default='semantic', type=str, help='choose task: semantic, depth')
pars... | 6,370 | 43.552448 | 120 | py |
sdmgrad | sdmgrad-main/cityscapes/evaluate.py | import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np
import torch
methods = [
"sdmgrad-1e-1", "sdmgrad-2e-1", "sdmgrad-3e-1", "sdmgrad-4e-1", "sdmgrad-5e-1", "sdmgrad-6e-1", "sdmgrad-7e-1",
"sdmgrad-8e-1", "sdmgrad-9e-1", "sdmgrad-1e0"
]
colors = ["C0", "C1", "C2", "C3", "C4", "C5", "C6", ... | 3,545 | 30.380531 | 117 | py |
sdmgrad | sdmgrad-main/cityscapes/model_segnet_stan.py | import torch.nn as nn
import torch.optim as optim
import torch.nn.functional as F
import argparse
from create_dataset import *
from utils import *
parser = argparse.ArgumentParser(description='Single-task: Attention Network')
parser.add_argument('--task', default='semantic', type=str, help='choose task: semantic, dep... | 11,156 | 49.713636 | 119 | py |
sdmgrad | sdmgrad-main/cityscapes/utils.py | import torch
import torch.nn.functional as F
import numpy as np
import random
import time
from copy import deepcopy
from min_norm_solvers import MinNormSolver
from scipy.optimize import minimize, Bounds, minimize_scalar
def euclidean_proj_simplex(v, s=1):
""" Compute the Euclidean projection on a positive simple... | 27,394 | 40.25753 | 148 | py |
sdmgrad | sdmgrad-main/cityscapes/model_segnet_split.py | import torch.nn as nn
import torch.optim as optim
import torch.nn.functional as F
import argparse
import torch.utils.data.sampler as sampler
from create_dataset import *
from utils import *
parser = argparse.ArgumentParser(description='Multi-task: Split')
parser.add_argument('--type', default='standard', type=str, he... | 11,395 | 50.103139 | 119 | py |
sdmgrad | sdmgrad-main/cityscapes/min_norm_solvers.py | # This code is from
# Multi-Task Learning as Multi-Objective Optimization
# Ozan Sener, Vladlen Koltun
# Neural Information Processing Systems (NeurIPS) 2018
# https://github.com/intel-isl/MultiObjectiveOptimization
import numpy as np
import torch
class MinNormSolver:
MAX_ITER = 20
STOP_CRIT = 1e-5
def ... | 7,358 | 35.979899 | 147 | py |
sdmgrad | sdmgrad-main/cityscapes/model_segnet_mtan.py | import torch.nn as nn
import torch.optim as optim
import torch.nn.functional as F
import argparse
import torch.utils.data.sampler as sampler
from create_dataset import *
from utils import *
parser = argparse.ArgumentParser(description='Multi-task: Attention Network')
parser.add_argument('--weight', default='equal', t... | 11,396 | 49.879464 | 119 | py |
sdmgrad | sdmgrad-main/cityscapes/create_dataset.py | from torch.utils.data.dataset import Dataset
import os
import torch
import torch.nn.functional as F
import fnmatch
import numpy as np
import random
class RandomScaleCrop(object):
"""
Credit to Jialong Wu from https://github.com/lorenmt/mtan/issues/34.
"""
def __init__(self, scale=[1.0, 1.2, 1.5]):
... | 6,513 | 41.298701 | 127 | py |
sdmgrad | sdmgrad-main/cityscapes/model_segnet_cross.py | import torch.nn as nn
import torch.optim as optim
import torch.nn.functional as F
import argparse
import torch.utils.data.sampler as sampler
from create_dataset import *
from utils import *
parser = argparse.ArgumentParser(description='Multi-task: Cross')
parser.add_argument('--weight', default='equal', type=str, hel... | 9,044 | 48.42623 | 119 | py |
sdmgrad | sdmgrad-main/cityscapes/model_segnet_mt.py | import torch.nn as nn
import torch.optim as optim
import torch.nn.functional as F
import argparse
import torch.utils.data.sampler as sampler
from create_dataset import *
from utils import *
parser = argparse.ArgumentParser(description='Multi-task: Attention Network')
parser.add_argument('--method', default='sdmgrad',... | 12,105 | 49.865546 | 119 | py |
SyNet | SyNet-master/CenterNet/src/main.py | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import _init_paths
import os
import torch
import torch.utils.data
from opts import opts
from models.model import create_model, load_model, save_model
from models.data_parallel import DataParallel
from logger ... | 3,348 | 31.833333 | 78 | py |
SyNet | SyNet-master/CenterNet/src/test.py | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import _init_paths
import os
import json
import cv2
import numpy as np
import time
from progress.bar import Bar
import torch
from external.nms import soft_nms
from opts import opts
from logger import Logger
f... | 4,092 | 31.484127 | 78 | py |
SyNet | SyNet-master/CenterNet/src/tools/convert_hourglass_weight.py | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
MODEL_PATH = '../../models/ExtremeNet_500000.pkl'
OUT_PATH = '../../models/ExtremeNet_500000.pth'
import torch
state_dict = torch.load(MODEL_PATH)
key_map = {'t_heats': 'hm_t', 'l_heats': 'hm_l', 'b_heats': 'h... | 905 | 28.225806 | 69 | py |
SyNet | SyNet-master/CenterNet/src/lib/logger.py | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
# Code referenced from https://gist.github.com/gyglim/1f8dfb1b5c82627ae3efcfbbadb9f514
import os
import time
import sys
import torch
USE_TENSORBOARD = True
try:
import tensorboardX
print('Using tensorboardX... | 2,228 | 29.534247 | 86 | py |
SyNet | SyNet-master/CenterNet/src/lib/detectors/exdet.py | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import _init_paths
import os
import cv2
import numpy as np
from progress.bar import Bar
import time
import torch
from models.decode import exct_decode, agnex_ct_decode
from models.utils import flip_tensor
fr... | 5,063 | 37.363636 | 80 | py |
SyNet | SyNet-master/CenterNet/src/lib/detectors/ctdet.py | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import cv2
import numpy as np
from progress.bar import Bar
import time
import torch
try:
from external.nms import soft_nms
except:
print('NMS not imported! If you need it,'
' do \n cd $CenterNet_RO... | 3,674 | 36.886598 | 90 | py |
SyNet | SyNet-master/CenterNet/src/lib/detectors/ddd.py | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import cv2
import numpy as np
from progress.bar import Bar
import time
import torch
from models.decode import ddd_decode
from models.utils import flip_tensor
from utils.image import get_affine_transform
from ... | 4,013 | 36.867925 | 73 | py |
SyNet | SyNet-master/CenterNet/src/lib/detectors/multi_pose.py | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import cv2
import numpy as np
from progress.bar import Bar
import time
import torch
try:
from external.nms import soft_nms_39
except:
print('NMS not imported! If you need it,'
' do \n cd $CenterNet... | 3,923 | 37.097087 | 79 | py |
SyNet | SyNet-master/CenterNet/src/lib/detectors/base_detector.py | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import cv2
import numpy as np
from progress.bar import Bar
import time
import torch
from models.model import create_model, load_model
from utils.image import get_affine_transform
from utils.debugger import Deb... | 5,061 | 34.152778 | 78 | py |
SyNet | SyNet-master/CenterNet/src/lib/models/decode.py | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import torch
import torch.nn as nn
from .utils import _gather_feat, _transpose_and_gather_feat
def _nms(heat, kernel=3):
pad = (kernel - 1) // 2
hmax = nn.functional.max_pool2d(
heat, (kernel,... | 21,763 | 37.115587 | 79 | py |
SyNet | SyNet-master/CenterNet/src/lib/models/losses.py | # ------------------------------------------------------------------------------
# Portions of this code are from
# CornerNet (https://github.com/princeton-vl/CornerNet)
# Copyright (c) 2018, University of Michigan
# Licensed under the BSD 3-Clause License
# -------------------------------------------------------------... | 7,843 | 31.957983 | 80 | py |
SyNet | SyNet-master/CenterNet/src/lib/models/data_parallel.py | import torch
from torch.nn.modules import Module
from torch.nn.parallel.scatter_gather import gather
from torch.nn.parallel.replicate import replicate
from torch.nn.parallel.parallel_apply import parallel_apply
from .scatter_gather import scatter_kwargs
class _DataParallel(Module):
r"""Implements data parallelis... | 5,176 | 39.445313 | 101 | py |
SyNet | SyNet-master/CenterNet/src/lib/models/utils.py | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import torch
import torch.nn as nn
def _sigmoid(x):
y = torch.clamp(x.sigmoid_(), min=1e-4, max=1-1e-4)
return y
def _gather_feat(feat, ind, mask=None):
dim = feat.size(2)
ind = ind.unsqueeze(2)... | 1,571 | 30.44 | 65 | py |
SyNet | SyNet-master/CenterNet/src/lib/models/model.py | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import torchvision.models as models
import torch
import torch.nn as nn
import os
from .networks.msra_resnet import get_pose_net
from .networks.dlav0 import get_pose_net as get_dlav0
from .networks.pose_dla_dcn... | 3,415 | 34.216495 | 80 | py |
SyNet | SyNet-master/CenterNet/src/lib/models/scatter_gather.py | import torch
from torch.autograd import Variable
from torch.nn.parallel._functions import Scatter, Gather
def scatter(inputs, target_gpus, dim=0, chunk_sizes=None):
r"""
Slices variables into approximately equal chunks and
distributes them across given GPUs. Duplicates
references to objects that are n... | 1,535 | 38.384615 | 77 | py |
SyNet | SyNet-master/CenterNet/src/lib/models/networks/resnet_dcn.py | # ------------------------------------------------------------------------------
# Copyright (c) Microsoft
# Licensed under the MIT License.
# Written by Bin Xiao (Bin.Xiao@microsoft.com)
# Modified by Dequan Wang and Xingyi Zhou
# ------------------------------------------------------------------------------
from __f... | 10,054 | 33.553265 | 80 | py |
SyNet | SyNet-master/CenterNet/src/lib/models/networks/pose_dla_dcn.py | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
import math
import logging
import numpy as np
from os.path import join
import torch
from torch import nn
import torch.nn.functional as F
import torch.utils.model_zoo as model_zoo
from .DCNv2.dcn_v2 ... | 17,594 | 34.617409 | 106 | py |
SyNet | SyNet-master/CenterNet/src/lib/models/networks/msra_resnet.py | # ------------------------------------------------------------------------------
# Copyright (c) Microsoft
# Licensed under the MIT License.
# Written by Bin Xiao (Bin.Xiao@microsoft.com)
# Modified by Xingyi Zhou
# ------------------------------------------------------------------------------
from __future__ import a... | 10,167 | 35.185053 | 94 | py |
SyNet | SyNet-master/CenterNet/src/lib/models/networks/large_hourglass.py | # ------------------------------------------------------------------------------
# This code is base on
# CornerNet (https://github.com/princeton-vl/CornerNet)
# Copyright (c) 2018, University of Michigan
# Licensed under the BSD 3-Clause License
# ----------------------------------------------------------------------... | 9,942 | 32.033223 | 118 | py |
SyNet | SyNet-master/CenterNet/src/lib/models/networks/dlav0.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import math
from os.path import join
import torch
from torch import nn
import torch.utils.model_zoo as model_zoo
import numpy as np
BatchNorm = nn.BatchNorm2d
d... | 22,682 | 34.00463 | 86 | py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.