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 |
|---|---|---|---|---|---|---|
DiffProxy | DiffProxy-main/stylegan/metrics/metric_utils.py | # Copyright (c) 2021, NVIDIA CORPORATION & AFFILIATES. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this sof... | 11,936 | 41.632143 | 167 | py |
DiffProxy | DiffProxy-main/stylegan/metrics/equivariance.py | # Copyright (c) 2021, NVIDIA CORPORATION & AFFILIATES. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this sof... | 10,868 | 39.55597 | 165 | py |
DiffProxy | DiffProxy-main/stylegan/metrics/perceptual_path_length.py | # Copyright (c) 2021, NVIDIA CORPORATION & AFFILIATES. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this sof... | 5,256 | 40.722222 | 131 | py |
DiffProxy | DiffProxy-main/stylegan/metrics/metric_main.py | # Copyright (c) 2021, NVIDIA CORPORATION & AFFILIATES. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this sof... | 5,675 | 35.857143 | 147 | py |
DiffProxy | DiffProxy-main/stylegan/metrics/precision_recall.py | # Copyright (c) 2021, NVIDIA CORPORATION & AFFILIATES. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this sof... | 3,644 | 56.857143 | 159 | py |
DebuggableDeepNetworks | DebuggableDeepNetworks-main/main.py | import os, math, time
import torch as ch
import torch.nn as nn
from robustness.datasets import DATASETS
# be sure to pip install glm_saga, or clone the repo from
# https://github.com/madrylab/glm_saga
from glm_saga.elasticnet import glm_saga
import helpers.data_helpers as data_helpers
import helpers.feature_helper... | 7,330 | 48.533784 | 120 | py |
DebuggableDeepNetworks | DebuggableDeepNetworks-main/helpers/data_helpers.py | import os, sys
sys.path.append('..')
import numpy as np
import torch as ch
from torch.utils.data import TensorDataset
from robustness.datasets import DATASETS as VISION_DATASETS
from robustness.tools.label_maps import CLASS_DICT
from language.datasets import DATASETS as LANGUAGE_DATASETS
from language.models import LAN... | 5,692 | 40.554745 | 107 | py |
DebuggableDeepNetworks | DebuggableDeepNetworks-main/helpers/feature_helpers.py | import os, math, sys
sys.path.append('..')
import numpy as np
import torch as ch
from torch._utils import _accumulate
from torch.utils.data import Subset
from tqdm import tqdm
from robustness.model_utils import make_and_restore_model
from robustness.loaders import LambdaLoader
from transformers import AutoConfig
import... | 13,878 | 38.31728 | 107 | py |
DebuggableDeepNetworks | DebuggableDeepNetworks-main/helpers/nlp_helpers.py | import torch as ch
import numpy as np
from lime.lime_text import LimeTextExplainer
from tqdm import tqdm
from wordcloud import WordCloud
import matplotlib
import matplotlib.pyplot as plt
import seaborn as sns
sns.set_style('darkgrid')
import os
from collections import defaultdict
def make_lime_fn(model,val_set, pool... | 7,049 | 37.736264 | 124 | py |
DebuggableDeepNetworks | DebuggableDeepNetworks-main/helpers/vis_helpers.py | import sys
sys.path.append('./lucent')
import torch as ch
import torchvision
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
from functools import partial
from lucent.optvis import render, param, transform, objectives
from lime import lime_image
def plot_sparsity(results):
"""Function to v... | 7,415 | 41.62069 | 97 | py |
DebuggableDeepNetworks | DebuggableDeepNetworks-main/helpers/decisionlayer_helpers.py | import os
import numpy as np
import torch as ch
import pandas as pd
def load_glm(result_dir):
Nlambda = max([int(f.split('params')[1].split('.pth')[0])
for f in os.listdir(result_dir) if 'params' in f]) + 1
print(f"Loading regularization path of length {Nlambda}")
params_... | 2,735 | 38.085714 | 85 | py |
DebuggableDeepNetworks | DebuggableDeepNetworks-main/language/datasets.py | import pandas as pd
import torch
from torch.utils.data import Dataset
from transformers import AutoTokenizer, AutoConfig
from .jigsaw_loaders import JigsawDataOriginal
def DATASETS(dataset_name):
if dataset_name == 'sst': return SSTDataset
elif dataset_name.startswith('jigsaw'): return JigsawDataset
else:... | 4,062 | 35.603604 | 108 | py |
DebuggableDeepNetworks | DebuggableDeepNetworks-main/language/jigsaw_loaders.py | from torch.utils.data.dataset import Dataset
import torch
import pandas as pd
import numpy as np
import language.datasets
from tqdm import tqdm
class JigsawData(Dataset):
"""Dataloader for the Jigsaw Toxic Comment Classification Challenges.
If test_csv_file is None and create_val_set is True the train file
... | 7,960 | 30.717131 | 111 | py |
DebuggableDeepNetworks | DebuggableDeepNetworks-main/language/models.py | import torch
import torch.nn as nn
from transformers import BertModel, BertPreTrainedModel, BertForSequenceClassification, RobertaForSequenceClassification
LANGUAGE_MODEL_DICT = {
'sst': 'barissayil/bert-sentiment-analysis-sst',
'jigsaw-toxic': 'unitary/toxic-bert',
'jigsaw-severe_toxic': 'unitary/toxic-b... | 1,850 | 43.071429 | 120 | py |
fed_iot_guard | fed_iot_guard-main/src/main.py | from argparse import ArgumentParser
import torch.utils.data
from data import read_all_data, all_devices
from federated_util import *
from grid_search import run_grid_search
from supervised_data import get_client_supervised_initial_splitting
from test_hparams import test_hyperparameters
from unsupervised_data import g... | 13,742 | 58.493506 | 174 | py |
fed_iot_guard | fed_iot_guard-main/src/unsupervised_ml.py | from types import SimpleNamespace
from typing import List, Dict, Tuple, Union, Optional
import torch
import torch.nn as nn
from context_printer import Color
from context_printer import ContextPrinter as Ctp
# noinspection PyProtectedMember
from torch.utils.data import DataLoader
from architectures import Threshold
fr... | 8,557 | 42.663265 | 142 | py |
fed_iot_guard | fed_iot_guard-main/src/supervised_experiments.py | from types import SimpleNamespace
from typing import Tuple, List
import torch
from context_printer import Color
from context_printer import ContextPrinter as Ctp
# noinspection PyProtectedMember
from torch.utils.data import DataLoader
from architectures import BinaryClassifier, NormalizingModel
from data import Clien... | 9,851 | 53.733333 | 142 | py |
fed_iot_guard | fed_iot_guard-main/src/supervised_data.py | from types import SimpleNamespace
from typing import List, Tuple, Optional, Set
import numpy as np
import torch
import torch.utils
import torch.utils.data
# noinspection PyProtectedMember
from torch.utils.data import DataLoader, Dataset, TensorDataset
from data import multiclass_labels, ClientData, FederationData, sp... | 8,434 | 58.401408 | 150 | py |
fed_iot_guard | fed_iot_guard-main/src/supervised_ml.py | from types import SimpleNamespace
from typing import List, Union, Tuple, Optional
import torch
import torch.nn as nn
from context_printer import Color
from context_printer import ContextPrinter as Ctp
# noinspection PyProtectedMember
from torch.utils.data import DataLoader
from federated_util import model_poisoning, ... | 5,411 | 42.296 | 144 | py |
fed_iot_guard | fed_iot_guard-main/src/federated_util.py | from copy import deepcopy
from types import SimpleNamespace
from typing import List, Set, Tuple, Callable, Optional
import numpy as np
import torch
from context_printer import ContextPrinter as Ctp, Color
# noinspection PyProtectedMember
from torch.utils.data import DataLoader
from architectures import NormalizingMod... | 9,118 | 45.764103 | 149 | py |
fed_iot_guard | fed_iot_guard-main/src/unsupervised_data.py | from types import SimpleNamespace
from typing import Dict, Tuple, List, Optional
import torch
import torch.utils
import torch.utils.data
# noinspection PyProtectedMember
from torch.utils.data import DataLoader, Dataset, TensorDataset
from data import mirai_attacks, gafgyt_attacks, split_client_data, ClientData, Feder... | 8,206 | 57.205674 | 150 | py |
fed_iot_guard | fed_iot_guard-main/src/architectures.py | from typing import List
import torch
import torch.nn as nn
class SimpleAutoencoder(nn.Module):
def __init__(self, activation_function: nn.Module, hidden_layers: List[int], verbose: bool = False) -> None:
super(SimpleAutoencoder, self).__init__()
self.seq = nn.Sequential()
n_neurons_in = 1... | 2,644 | 34.743243 | 116 | py |
fed_iot_guard | fed_iot_guard-main/src/metrics.py | import torch
class BinaryClassificationResult:
def __init__(self, tp: int = 0, tn: int = 0, fp: int = 0, fn: int = 0):
self.tp = tp # Number of true positives
self.tn = tn # Number of true negatives
self.fp = fp # Number of false positives
self.fn = fn # Number of false negativ... | 4,003 | 38.643564 | 148 | py |
fed_iot_guard | fed_iot_guard-main/src/ml.py | from typing import Tuple, List
import torch
from context_printer import Color
from context_printer import ContextPrinter as Ctp
# noinspection PyProtectedMember
from torch.utils.data import DataLoader
from architectures import NormalizingModel
def get_sub_div(data: torch.Tensor, normalization: str) -> Tuple[torch.t... | 1,415 | 34.4 | 147 | py |
fed_iot_guard | fed_iot_guard-main/src/print_util.py | from typing import Optional
import torch
from context_printer import Color
from context_printer import ContextPrinter as Ctp
from metrics import BinaryClassificationResult
class Columns:
SMALL = 12
MEDIUM = 16
LARGE = 22
def print_federation_round(federation_round: int, n_rounds: int) -> None:
Ctp... | 3,996 | 48.345679 | 128 | py |
fed_iot_guard | fed_iot_guard-main/src/unsupervised_experiments.py | from types import SimpleNamespace
from typing import Tuple, List, Dict
import torch
from context_printer import Color
from context_printer import ContextPrinter as Ctp
# noinspection PyProtectedMember
from torch.utils.data import DataLoader
from architectures import SimpleAutoencoder, NormalizingModel, Threshold
from... | 12,192 | 57.620192 | 147 | py |
PMIC | PMIC-main/ma_utils.py |
import numpy as np
import scipy.signal
import torch
# from mpi_tools import mpi_statistics_scalar
# Code based on:
# https://github.com/openai/baselines/blob/master/baselines/deepq/replay_buffer.py
# Expects tuples of (state, next_state, action, reward, done)
class ReplayBuffer(object):
def __init__(self, max_... | 24,339 | 37.696343 | 153 | py |
PMIC | PMIC-main/run_maxminMADDPG.py | '''
Demo run file for different algorithms and Mujoco tasks.
'''
import numpy as np
import torch
import gym
import argparse
import ma_utils
import algorithms.mpe_new_maxminMADDPG as MA_MINE_DDPG
import math
import os
from tensorboardX import SummaryWriter
from multiprocessing import cpu_count
from maddpg.uti... | 15,980 | 36.602353 | 251 | py |
PMIC | PMIC-main/algorithms/mpe_new_maxminMADDPG.py | import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
import math
from collections import OrderedDict
from torch.autograd import Variable
import os
from torch import Tensor
class OUNoise:
def __init__(self, action_dimension, scale=0.1, mu=0, theta=0.15, sigma=0.2):
self.act... | 50,748 | 48.51122 | 401 | py |
PMIC | PMIC-main/multiagent/envs/mujoco_multi.py | import numpy as np
import gym
from gym import spaces
from gym.spaces import Box
from multiagent.environment import MultiAgentEnv
from multiagent.envs import obsk
# using code from https://github.com/ikostrikov/pytorch-ddpg-naf
class NormalizedActions(gym.ActionWrapper):
def _action(self, action):
action =... | 6,894 | 38.176136 | 135 | py |
PMIC | PMIC-main/multiagent/envs/half_cheetah_multi.py | import numpy as np
import gym
from gym import spaces
from gym.spaces import Box
from multiagent.environment import MultiAgentEnv
from multiagent.envs import obsk
# using code from https://github.com/ikostrikov/pytorch-ddpg-naf
class NormalizedActions(gym.ActionWrapper):
def _action(self, action):
action =... | 7,849 | 39.885417 | 135 | py |
PMIC | PMIC-main/maddpg/utils/agents.py | from torch import Tensor
from torch.autograd import Variable
from torch.optim import Adam
from .networks import MLPNetwork
from .misc import hard_update, gumbel_softmax, onehot_from_logits
from .noise import OUNoise
class DDPGAgent(object):
"""
General class for DDPG agents (policy, critic, target policy, targ... | 4,096 | 41.677083 | 77 | py |
PMIC | PMIC-main/maddpg/utils/misc.py | import os
import torch
import torch.nn.functional as F
import torch.distributed as dist
from torch.autograd import Variable
import numpy as np
# https://github.com/ikostrikov/pytorch-ddpg-naf/blob/master/ddpg.py#L11
def soft_update(target, source, tau):
"""
Perform DDPG soft update (move target params toward s... | 4,043 | 42.483871 | 106 | py |
PMIC | PMIC-main/maddpg/utils/networks.py | import torch.nn as nn
import torch.nn.functional as F
class MLPNetwork(nn.Module):
"""
MLP network (can be used as value or policy)
"""
def __init__(self, input_dim, out_dim, hidden_dim=64, nonlin=F.relu,
constrain_out=False, norm_in=True, discrete_action=True):
"""
Inp... | 1,700 | 35.978261 | 77 | py |
PMIC | PMIC-main/maddpg/utils/buffer.py | import numpy as np
from torch import Tensor
from torch.autograd import Variable
class ReplayBuffer(object):
"""
Replay Buffer for multi-agent RL with parallel rollouts
"""
def __init__(self, max_steps, num_agents, obs_dims, ac_dims):
"""
Inputs:
max_steps (int): Maximum numb... | 4,794 | 48.43299 | 93 | py |
DeepVO-pytorch | DeepVO-pytorch-master/main.py | import torch
from torch.utils.data import DataLoader
import numpy as np
import os
import time
import pandas as pd
from params import par
from model import DeepVO
from data_helper import get_data_info, SortedRandomBatchSampler, ImageSequenceDataset, get_partition_data_info
# Write all hyperparameters to record_path
mo... | 6,026 | 39.18 | 173 | py |
DeepVO-pytorch | DeepVO-pytorch-master/test.py | # predicted as a batch
from params import par
from model import DeepVO
import numpy as np
from PIL import Image
import glob
import os
import time
import torch
from data_helper import get_data_info, ImageSequenceDataset
from torch.utils.data import DataLoader
from helper import eulerAnglesToRotationMatrix
if __name__ =... | 4,249 | 31.442748 | 140 | py |
DeepVO-pytorch | DeepVO-pytorch-master/Dataloader_loss.py | # %load Dataloader_loss.py
# In[ ]:
from params import par
from model import DeepVO
import cv2
import math
import numpy as np
import time
import torch
import os
from torch.autograd import Variable
from torch.utils.data import Dataset
from torch.utils.data import DataLoader
from torch.nn.modules import loss
from t... | 4,367 | 32.090909 | 196 | py |
DeepVO-pytorch | DeepVO-pytorch-master/model.py | import torch
import torch.nn as nn
from params import par
from torch.autograd import Variable
from torch.nn.init import kaiming_normal_, orthogonal_
import numpy as np
def conv(batchNorm, in_planes, out_planes, kernel_size=3, stride=1, dropout=0):
if batchNorm:
return nn.Sequential(
nn.Conv2d(i... | 5,583 | 40.984962 | 125 | py |
DeepVO-pytorch | DeepVO-pytorch-master/data_helper.py | import os
import glob
import pandas as pd
import numpy as np
from PIL import Image
import torch
from torch.utils.data import Dataset, DataLoader
from torch.utils.data.sampler import Sampler
from torchvision import transforms
import time
from params import par
from helper import normalize_angle_delta
def get_data_info... | 11,628 | 41.753676 | 145 | py |
DeepVO-pytorch | DeepVO-pytorch-master/preprocess.py | import os
import glob
import numpy as np
import time
from helper import R_to_angle
from params import par
from torchvision import transforms
from PIL import Image
import torch
import math
def clean_unused_images():
seq_frame = {'00': ['000', '004540'],
'01': ['000', '001100'],
'02': ['000', '004660'],
'03... | 4,086 | 32.77686 | 196 | py |
Human-Segmentation-PyTorch | Human-Segmentation-PyTorch-master/inference_webcam.py | #------------------------------------------------------------------------------
# Libraries
#------------------------------------------------------------------------------
import torch, argparse
from models import UNet
from base import VideoInference
#------------------------------------------------------------------... | 1,479 | 31.173913 | 79 | py |
Human-Segmentation-PyTorch | Human-Segmentation-PyTorch-master/measure_model.py | #------------------------------------------------------------------------------
# Libraries
#------------------------------------------------------------------------------
import os
os.environ['CUDA_VISIBLE_DEVICES'] = '-1'
import models
import argparse
from time import time
import torch
from torchsummary import sum... | 2,782 | 26.554455 | 96 | py |
Human-Segmentation-PyTorch | Human-Segmentation-PyTorch-master/train.py | #------------------------------------------------------------------------------
# Libraries
#------------------------------------------------------------------------------
import os, json, argparse, torch, warnings
warnings.filterwarnings("ignore")
import models as module_arch
import evaluation.losses as module_loss... | 3,462 | 32.95098 | 109 | py |
Human-Segmentation-PyTorch | Human-Segmentation-PyTorch-master/inference_video.py | #------------------------------------------------------------------------------
# Libraries
#------------------------------------------------------------------------------
import cv2, torch, argparse
from time import time
import numpy as np
from torch.nn import functional as F
from models import UNet
from dataloaders ... | 4,860 | 32.993007 | 155 | py |
Human-Segmentation-PyTorch | Human-Segmentation-PyTorch-master/trainer/trainer.py | #------------------------------------------------------------------------------
# Libraries
#------------------------------------------------------------------------------
import warnings
warnings.filterwarnings("ignore")
import torch
import numpy as np
from tqdm import tqdm
import torch.nn.functional as F
from torc... | 6,325 | 34.943182 | 130 | py |
Human-Segmentation-PyTorch | Human-Segmentation-PyTorch-master/evaluation/losses.py | #------------------------------------------------------------------------------
# Libraries
#------------------------------------------------------------------------------
import torch
import torch.nn.functional as F
#------------------------------------------------------------------------------
# Fundamental los... | 4,073 | 35.702703 | 113 | py |
Human-Segmentation-PyTorch | Human-Segmentation-PyTorch-master/evaluation/metrics.py | #------------------------------------------------------------------------------
# Libraries
#------------------------------------------------------------------------------
import torch
from torch.nn import functional as F
#------------------------------------------------------------------------------
# Fundamenta... | 3,235 | 36.195402 | 107 | py |
Human-Segmentation-PyTorch | Human-Segmentation-PyTorch-master/models/ICNet.py | #------------------------------------------------------------------------------
# Libraries
#------------------------------------------------------------------------------
import torch
import torch.nn as nn
import torch.nn.functional as F
from collections import OrderedDict
from base.base_model import BaseModel
from ... | 6,572 | 32.707692 | 129 | py |
Human-Segmentation-PyTorch | Human-Segmentation-PyTorch-master/models/BiSeNet.py | #------------------------------------------------------------------------------
# Libraries
#------------------------------------------------------------------------------
import torch
import torch.nn as nn
import torch.nn.functional as F
from base.base_model import BaseModel
from models.backbonds import ResNet
#--... | 6,044 | 34.769231 | 121 | py |
Human-Segmentation-PyTorch | Human-Segmentation-PyTorch-master/models/DeepLab.py | #------------------------------------------------------------------------------
# Libraries
#------------------------------------------------------------------------------
import torch
import torch.nn as nn
import torch.nn.functional as F
from base.base_model import BaseModel
from models.backbonds import ResNet, VGG
... | 5,781 | 30.254054 | 131 | py |
Human-Segmentation-PyTorch | Human-Segmentation-PyTorch-master/models/UNet.py | #------------------------------------------------------------------------------
# Libraries
#------------------------------------------------------------------------------
import torch
import torch.nn as nn
import torch.nn.functional as F
from functools import reduce
from base import BaseModel
from models.backbonds ... | 6,045 | 35.865854 | 97 | py |
Human-Segmentation-PyTorch | Human-Segmentation-PyTorch-master/models/PSPNet.py | #------------------------------------------------------------------------------
# Libraries
#------------------------------------------------------------------------------
import torch
import torch.nn as nn
import torch.nn.functional as F
from collections import OrderedDict
from base.base_model import BaseModel
from ... | 4,624 | 32.759124 | 106 | py |
Human-Segmentation-PyTorch | Human-Segmentation-PyTorch-master/models/UNetPlus.py | #------------------------------------------------------------------------------
# Libraries
#------------------------------------------------------------------------------
import torch
import torch.nn as nn
import torch.nn.functional as F
from collections import OrderedDict
from base import BaseModel
from models imp... | 5,685 | 40.202899 | 145 | py |
Human-Segmentation-PyTorch | Human-Segmentation-PyTorch-master/models/backbonds/ResNet.py | #------------------------------------------------------------------------------
# Libraries
#------------------------------------------------------------------------------
import torch
import torch.nn as nn
from base import BaseBackbone
#------------------------------------------------------------------------------... | 6,894 | 28.216102 | 126 | py |
Human-Segmentation-PyTorch | Human-Segmentation-PyTorch-master/models/backbonds/Xception.py | """
Creates an Xception Model as defined in:
Francois Chollet
Xception: Deep Learning with Depthwise Separable Convolutions
https://arxiv.org/pdf/1610.02357.pdf
This weights ported from the Keras implementation. Achieves the following performance on the validation set:
Loss:0.9173 Prec@1:78.892 Prec@5:94.292
REMEM... | 6,776 | 32.885 | 127 | py |
Human-Segmentation-PyTorch | Human-Segmentation-PyTorch-master/models/backbonds/VGG.py | #------------------------------------------------------------------------------
# Libraries
#------------------------------------------------------------------------------
import torch
import torch.nn as nn
#------------------------------------------------------------------------------
# Class of VGG
#-----------... | 5,231 | 29.596491 | 100 | py |
Human-Segmentation-PyTorch | Human-Segmentation-PyTorch-master/models/backbonds/MobileNetV2.py | #------------------------------------------------------------------------------
# Libraries
#------------------------------------------------------------------------------
import math, torch, json
import torch.nn as nn
from functools import reduce
#--------------------------------------------------------------------... | 5,462 | 28.370968 | 102 | py |
Human-Segmentation-PyTorch | Human-Segmentation-PyTorch-master/models/backbones/efficientnet.py | #------------------------------------------------------------------------------
# Libraries
#------------------------------------------------------------------------------
from base import BaseBackbone
from timm.models.gen_efficientnet import (
InvertedResidual, default_cfgs, load_pretrained, _round_channels,
_decod... | 10,267 | 36.889299 | 108 | py |
Human-Segmentation-PyTorch | Human-Segmentation-PyTorch-master/models/backbones/resnet.py | #------------------------------------------------------------------------------
# Libraries
#------------------------------------------------------------------------------
from base import BaseBackboneWrapper
from timm.models.resnet import ResNet as BaseResNet
from timm.models.resnet import default_cfgs, load_pretrain... | 13,998 | 37.353425 | 96 | py |
Human-Segmentation-PyTorch | Human-Segmentation-PyTorch-master/dataloaders/dataloader.py | #------------------------------------------------------------------------------
# Libraries
#------------------------------------------------------------------------------
import warnings
warnings.filterwarnings('ignore')
import cv2, os
import numpy as np
from random import shuffle
import torch
from torch.utils.dat... | 5,338 | 32.791139 | 121 | py |
Human-Segmentation-PyTorch | Human-Segmentation-PyTorch-master/base/base_model.py | #------------------------------------------------------------------------------
# Libraries
#------------------------------------------------------------------------------
import torch
import torch.nn as nn
import torchsummary
import os, warnings, sys
from utils import add_flops_counting_methods, flops_to_string
#... | 4,728 | 34.556391 | 90 | py |
Human-Segmentation-PyTorch | Human-Segmentation-PyTorch-master/base/base_trainer.py | #------------------------------------------------------------------------------
# Libraries
#------------------------------------------------------------------------------
from time import time
import os, math, json, logging, datetime, torch
from utils.visualization import WriterTensorboardX
#----------------------... | 7,855 | 37.321951 | 133 | py |
Human-Segmentation-PyTorch | Human-Segmentation-PyTorch-master/base/base_data_loader.py | #------------------------------------------------------------------------------
# Libraries
#------------------------------------------------------------------------------
import numpy as np
from torch.utils.data import DataLoader
from torch.utils.data.dataloader import default_collate
from torch.utils.data.sampler i... | 2,097 | 32.83871 | 112 | py |
Human-Segmentation-PyTorch | Human-Segmentation-PyTorch-master/base/base_inference.py | #------------------------------------------------------------------------------
# Libraries
#------------------------------------------------------------------------------
import cv2, torch
import numpy as np
from time import time
from torch.nn import functional as F
#-----------------------------------------------... | 5,113 | 28.560694 | 112 | py |
Human-Segmentation-PyTorch | Human-Segmentation-PyTorch-master/utils/utils.py | #------------------------------------------------------------------------------
# Libraries
#------------------------------------------------------------------------------
import os, cv2, torch
import numpy as np
from dataloaders import transforms
#---------------------------------------------------------------------... | 2,506 | 35.333333 | 114 | py |
Human-Segmentation-PyTorch | Human-Segmentation-PyTorch-master/utils/flops_counter.py | import torch.nn as nn
import torch
import numpy as np
def flops_to_string(flops):
if flops // 10**9 > 0:
return str(round(flops / 10.**9, 2)) + 'GMac'
elif flops // 10**6 > 0:
return str(round(flops / 10.**6, 2)) + 'MMac'
elif flops // 10**3 > 0:
return str(round(flops / 10.**3, 2))... | 8,546 | 31.131579 | 100 | py |
CDTrans | CDTrans-master/train.py | import os
from torch.backends import cudnn
from utils.logger import setup_logger
from datasets import make_dataloader
from model import make_model
from solver import make_optimizer, create_scheduler
from loss import make_loss
from processor import do_train_pretrain, do_train_uda
import random
import torch
import numpy ... | 4,936 | 36.401515 | 194 | py |
CDTrans | CDTrans-master/solver/lr_scheduler.py | # encoding: utf-8
"""
@author: liaoxingyu
@contact: sherlockliao01@gmail.com
"""
from bisect import bisect_right
import torch
# FIXME ideally this would be achieved with a CombinedLRScheduler,
# separating MultiStepLR with WarmupLR
# but the current LRScheduler design doesn't allow it
# from .scheduler import Schedu... | 2,119 | 31.615385 | 80 | py |
CDTrans | CDTrans-master/solver/cosine_lr.py | """ Cosine Scheduler
Cosine LR schedule with warmup, cycle/restarts, noise.
Hacked together by / Copyright 2020 Ross Wightman
"""
import logging
import math
import torch
from .scheduler import Scheduler
_logger = logging.getLogger(__name__)
class CosineLRScheduler(Scheduler):
"""
Cosine decay with restarts... | 3,954 | 34.3125 | 121 | py |
CDTrans | CDTrans-master/solver/scheduler.py | from typing import Dict, Any
import torch
class Scheduler:
""" Parameter Scheduler Base Class
A scheduler base class that can be used to schedule any optimizer parameter groups.
Unlike the builtin PyTorch schedulers, this is intended to be consistently called
* At the END of each epoch, before increm... | 4,745 | 45.990099 | 112 | py |
CDTrans | CDTrans-master/solver/make_optimizer.py | import torch
def make_optimizer(cfg, model, center_criterion):
params = []
for key, value in model.named_parameters():
if not value.requires_grad:
continue
lr = cfg.SOLVER.BASE_LR
weight_decay = cfg.SOLVER.WEIGHT_DECAY
if "bias" in key:
lr = cfg.SOLVER.B... | 1,376 | 42.03125 | 106 | py |
CDTrans | CDTrans-master/processor/processor_uda.py | import logging
from typing import OrderedDict
import numpy as np
import os
import time
import torch
import torch.nn as nn
import cv2
from utils.meter import AverageMeter
from utils.metrics import R1_mAP, R1_mAP_eval, R1_mAP_Pseudo, R1_mAP_query_mining, R1_mAP_save_feature, R1_mAP_draw_figure, Class_accuracy_eval
from u... | 25,813 | 45.178891 | 243 | py |
CDTrans | CDTrans-master/processor/processor.py | import logging
import numpy as np
import os
import time
import torch
import torch.nn as nn
import cv2
from utils.meter import AverageMeter
from utils.metrics import R1_mAP, R1_mAP_eval, R1_mAP_Pseudo, R1_mAP_query_mining, R1_mAP_save_feature, R1_mAP_draw_figure, Class_accuracy_eval
from torch.nn.parallel import Distrib... | 11,714 | 43.041353 | 143 | py |
CDTrans | CDTrans-master/datasets/make_dataloader.py | # from transformer_normal_DA_v0.datasets.office import Office
import torch
import torchvision.transforms as T
from torch.utils.data import DataLoader
from .bases import ImageDataset
from .preprocessing import RandomErasing
# from timm.data.random_erasing import RandomErasing
from .sampler import RandomIdentitySampler
f... | 8,793 | 39.525346 | 170 | py |
CDTrans | CDTrans-master/datasets/sampler.py | from torch.utils.data.sampler import Sampler
from collections import defaultdict
import copy
import random
import numpy as np
class RandomIdentitySampler(Sampler):
"""
Randomly sample N identities, then for each identity,
randomly sample K instances, therefore batch size is N*K.
Args:
- data_source... | 2,543 | 35.342857 | 84 | py |
CDTrans | CDTrans-master/datasets/sampler_ddp.py | from torch.utils.data.sampler import Sampler
from collections import defaultdict
import copy
import random
import numpy as np
import math
import torch.distributed as dist
_LOCAL_PROCESS_GROUP = None
import torch
import pickle
def _get_global_gloo_group():
"""
Return a process group based on gloo backend, conta... | 7,051 | 34.616162 | 167 | py |
CDTrans | CDTrans-master/datasets/bases.py | from PIL import Image, ImageFile
from torch.utils.data import Dataset
import os.path as osp
ImageFile.LOAD_TRUNCATED_IMAGES = True
def read_image(img_path):
"""Keep reading image until succeed.
This can avoid IOError incurred by heavy IO process."""
got_img = False
if not osp.exists(img_path):
... | 3,770 | 34.575472 | 112 | py |
CDTrans | CDTrans-master/loss/metric_learning.py | import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.autograd
from torch.nn import Parameter
import math
class ContrastiveLoss(nn.Module):
def __init__(self, margin=0.3, **kwargs):
super(ContrastiveLoss, self).__init__()
self.margin = margin
def forward(self, inputs... | 7,001 | 36.047619 | 121 | py |
CDTrans | CDTrans-master/loss/softmax_loss.py | import torch
import torch.nn as nn
class CrossEntropyLabelSmooth(nn.Module):
"""Cross entropy loss with label smoothing regularizer.
Reference:
Szegedy et al. Rethinking the Inception Architecture for Computer Vision. CVPR 2016.
Equation: y = (1 - epsilon) * y + epsilon / K.
Args:
num_cla... | 1,241 | 35.529412 | 95 | py |
CDTrans | CDTrans-master/loss/mmd_loss.py | import torch
import torch.nn as nn
class MMD_loss(nn.Module):
def __init__(self, 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
return
def guassian_kernel(self, source, ... | 1,636 | 43.243243 | 136 | py |
CDTrans | CDTrans-master/loss/triplet_loss.py | import torch
from torch import nn
def normalize(x, axis=-1):
"""Normalizing to unit length along the specified dimension.
Args:
x: pytorch Variable
Returns:
x: pytorch Variable, same shape as input
"""
x = 1. * x / (torch.norm(x, 2, axis, keepdim=True).expand_as(x) + 1e-12)
return ... | 4,748 | 33.413043 | 82 | py |
CDTrans | CDTrans-master/loss/arcface.py | import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.nn import Parameter
import math
class ArcFace(nn.Module):
def __init__(self, in_features, out_features, s=30.0, m=0.50, bias=False):
super(ArcFace, self).__init__()
self.in_features = in_features
self.out_feature... | 2,975 | 36.2 | 105 | py |
CDTrans | CDTrans-master/loss/center_loss.py | from __future__ import absolute_import
import torch
from torch import nn
class CenterLoss(nn.Module):
"""Center loss.
Reference:
Wen et al. A Discriminative Feature Learning Approach for Deep Face Recognition. ECCV 2016.
Args:
num_classes (int): number of classes.
feat_dim (int): fe... | 2,335 | 33.352941 | 110 | py |
CDTrans | CDTrans-master/loss/make_loss.py | # encoding: utf-8
"""
@author: liaoxingyu
@contact: sherlockliao01@gmail.com
"""
import torch
import torch.nn.functional as F
from .softmax_loss import CrossEntropyLabelSmooth
from .triplet_loss import TripletLoss
from .center_loss import CenterLoss
from .mmd_loss import MMD_loss
def make_loss(cfg, num_classes):
... | 1,569 | 35.511628 | 106 | py |
CDTrans | CDTrans-master/utils/reranking.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri, 25 May 2018 20:29:09
@author: luohao
"""
"""
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-I... | 8,071 | 45.65896 | 119 | py |
CDTrans | CDTrans-master/utils/metrics.py | import torch
import numpy as np
import torch.nn as nn
import os
from utils.reranking import re_ranking,re_ranking_numpy
from scipy.spatial.distance import cdist
import torch.nn.functional as F
from sklearn.metrics import confusion_matrix
def euclidean_distance(qf, gf):
m = qf.shape[0]
n = gf.shape[0]
dist... | 19,489 | 36.625483 | 115 | py |
CDTrans | CDTrans-master/model/make_model.py | import torch
import torch.nn as nn
from .backbones.resnet import ResNet, BasicBlock, Bottleneck
from loss.arcface import ArcFace
from .backbones.resnet_ibn_a import resnet50_ibn_a,resnet101_ibn_a
from .backbones.se_resnet_ibn_a import se_resnet101_ibn_a
from .backbones.vit_pytorch import vit_base_patch16_224_TransReID,... | 20,400 | 48.040865 | 322 | py |
CDTrans | CDTrans-master/model/backbones/vit_pytorch.py | """ Vision Transformer (ViT) in PyTorch
A PyTorch implement of Vision Transformers as described in
'An Image Is Worth 16 x 16 Words: Transformers for Image Recognition at Scale' - https://arxiv.org/abs/2010.11929
The official jax code is released and available at https://github.com/google-research/vision_transformer
... | 32,752 | 42.554521 | 174 | py |
CDTrans | CDTrans-master/model/backbones/se_module.py | from torch import nn
class SELayer(nn.Module):
def __init__(self, channel, reduction=16):
super(SELayer, self).__init__()
self.avg_pool = nn.AdaptiveAvgPool2d(1)
self.fc = nn.Sequential(
nn.Linear(channel, int(channel/reduction), bias=False),
nn.ReLU(inplace... | 609 | 31.105263 | 71 | py |
CDTrans | CDTrans-master/model/backbones/resnet.py | import math
import torch
from torch import nn
def conv3x3(in_planes, out_planes, stride=1):
"""3x3 convolution with padding"""
return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride,
padding=1, bias=False)
class BasicBlock(nn.Module):
expansion = 1
def __init__(s... | 5,721 | 31.885057 | 95 | py |
CDTrans | CDTrans-master/model/backbones/vit_pytorch_uda.py | """ Vision Transformer (ViT) in PyTorch
A PyTorch implement of Vision Transformers as described in
'An Image Is Worth 16 x 16 Words: Transformers for Image Recognition at Scale' - https://arxiv.org/abs/2010.11929
The official jax code is released and available at https://github.com/google-research/vision_transformer
... | 29,841 | 43.942771 | 192 | py |
CDTrans | CDTrans-master/model/backbones/se_resnet_ibn_a.py | from .se_module import SELayer
import torch.nn as nn
import torch
import math
from collections import OrderedDict
import torch.utils.checkpoint as cp
__all__ = ['se_resnet50_ibn_a', 'se_resnet101_ibn_a', 'se_resnet152_ibn_a']
def conv3x3(in_planes, out_planes, stride=1):
return nn.Conv2d(in_planes, out_planes, ker... | 7,446 | 31.662281 | 96 | py |
CDTrans | CDTrans-master/model/backbones/resnet_ibn_a.py | import torch
import torch.nn as nn
import math
import torch.utils.model_zoo as model_zoo
import torch.nn.functional as F
__all__ = ['ResNet_IBN', 'resnet50_ibn_a', 'resnet101_ibn_a',
'resnet152_ibn_a']
model_urls = {
'resnet50': 'https://download.pytorch.org/models/resnet50-19c8e357.pth',
'resnet1... | 6,681 | 32.747475 | 90 | py |
monotone_op_net | monotone_op_net-master/mon.py | import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
class MONSingleFc(nn.Module):
""" Simple MON linear class, just a single full multiply. """
def __init__(self, in_dim, out_dim, m=1.0):
super().__init__()
self.U = nn.Linear(in_dim, out_dim)
self.A =... | 17,466 | 38.788155 | 116 | py |
monotone_op_net | monotone_op_net-master/splitting.py | import torch
import torch.nn as nn
from torch.autograd import Function
import utils
import time
class MONForwardBackwardSplitting(nn.Module):
def __init__(self, linear_module, nonlin_module, alpha=1.0, tol=1e-5, max_iter=50, verbose=False):
super().__init__()
self.linear_module = linear_module
... | 8,149 | 37.262911 | 108 | py |
monotone_op_net | monotone_op_net-master/utils.py | import torch
import numpy as np
from train import cuda
class Meter(object):
"""Computes and stores the min, max, avg, and current values"""
def __init__(self):
self.reset()
def reset(self):
self.val = 0
self.avg = 0
self.sum = 0
self.count = 0
self.max = -f... | 2,684 | 31.743902 | 105 | py |
monotone_op_net | monotone_op_net-master/train.py | import torch
import torch.nn as nn
import torch.nn.functional as F
import torchvision.datasets as dset
import torchvision.transforms as transforms
from torch.utils.data import DataLoader
import torch.optim as optim
import mon
import numpy as np
import time
def cuda(tensor):
if torch.cuda.is_available():
re... | 10,630 | 36.041812 | 101 | py |
teacher-perception | teacher-perception-master/code/utils.py | import numpy as np
import pandas as pd
import xgboost as xgb
from sklearn.datasets import load_svmlight_files
np.random.seed(1)
from collections import defaultdict
from copy import deepcopy
from scipy.stats import chisquare
import os
from sklearn.preprocessing import LabelEncoder
from sklearn.feature_selection impor... | 144,353 | 40.067994 | 234 | py |
teacher-perception | teacher-perception-master/code/word_order.py | import os, pyconll
import dataloader_word_order as dataloader
import argparse
import numpy as np
np.random.seed(1)
import sklearn
import sklearn.tree
from collections import defaultdict
import pandas as pd
from sklearn.metrics import accuracy_score
from sklearn.model_selection import GridSearchCV
import utils
from ... | 42,613 | 51.609877 | 279 | py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.