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 |
|---|---|---|---|---|---|---|
CircleNet | CircleNet-master/src/lib/datasets/dataset/monuseg.py | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import pycocotools.coco as coco
import datasets.eval_protocals.kidpath_circle as kidpath_circle
from datasets.eval_protocals.circle_eval import CIRCLEeval
from pycocotools.cocoeval import COCOeval
import numpy... | 6,881 | 39.721893 | 82 | py |
CircleNet | CircleNet-master/src/lib/datasets/dataset/kidney_first_batch_081617_ADE.py | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import pycocotools.coco as coco
import datasets.eval_protocals.kidpath_circle as kidpath_circle
from datasets.eval_protocals.circle_eval import CIRCLEeval
from pycocotools.cocoeval import COCOeval
import numpy... | 7,194 | 40.831395 | 101 | py |
CircleNet | CircleNet-master/src/lib/datasets/dataset/pascal.py | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import pycocotools.coco as coco
import numpy as np
import torch
import json
import os
import torch.utils.data as data
class PascalVOC(data.Dataset):
num_classes = 20
default_resolution = [384, 384]
mean... | 3,032 | 35.542169 | 80 | py |
CircleNet | CircleNet-master/src/lib/datasets/dataset/kidney_first_batch_R24.py | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import pycocotools.coco as coco
import datasets.eval_protocals.kidpath_circle as kidpath_circle
from datasets.eval_protocals.circle_eval import CIRCLEeval
from pycocotools.cocoeval import COCOeval
import numpy... | 7,507 | 41.659091 | 157 | py |
CircleNet | CircleNet-master/src/lib/datasets/dataset/kidpath_old.py | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import pycocotools.coco as coco
from pycocotools.cocoeval import COCOeval
import numpy as np
import json
import os
import torch.utils.data as data
class KidPath_old(data.Dataset):
num_classes = 2
default_... | 4,223 | 35.730435 | 78 | py |
CircleNet | CircleNet-master/src/lib/datasets/dataset/coco.py | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import pycocotools.coco as coco
from pycocotools.cocoeval import COCOeval
import numpy as np
import json
import os
import torch.utils.data as data
class COCO(data.Dataset):
num_classes = 80
default_resolu... | 5,214 | 39.115385 | 78 | py |
CircleNet | CircleNet-master/src/lib/datasets/dataset/kidpath.py | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import pycocotools.coco as coco
import datasets.eval_protocals.kidpath_circle as kidpath_circle
from datasets.eval_protocals.circle_eval import CIRCLEeval
from pycocotools.cocoeval import COCOeval
import numpy... | 7,048 | 39.982558 | 82 | py |
CircleNet | CircleNet-master/src/lib/utils/utils.py | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import torch
class AverageMeter(object):
"""Computes and stores the average and current value"""
def __init__(self):
self.reset()
def reset(self):
self.val = 0
self.avg = 0... | 542 | 22.608696 | 59 | py |
Gym-ATC-Attack-Project | Gym-ATC-Attack-Project-main/attacks/uni_attack_v1.py | import torch
from torch import nn
from attacks.attack_v1 import Attack, Variable
class UniAttack(Attack):
def __init__(self, env, device, agent, load_path, epsilon, atk, episodes, method, frq=1.0):
super().__init__(env, device, agent, load_path, epsilon, atk, episodes, method)
self.frq = frq
... | 1,015 | 35.285714 | 95 | py |
Gym-ATC-Attack-Project | Gym-ATC-Attack-Project-main/attacks/main_v2.py | import random
import numpy as np
import torch
from attacks.attack_v2 import Attack
from attacks.st_attack_v2 import STAttack
from attacks.uni_attack_v2 import UniAttack
from envs.SimpleATC_env_global_v2 import SimpleEnvV2
from envs.SimpleATC_env_local_v2 import SimpleEnvLocalV2
from models.dqn_model import QNetwork,... | 3,186 | 43.263889 | 121 | py |
Gym-ATC-Attack-Project | Gym-ATC-Attack-Project-main/attacks/attack_v2.py | import os
import random
from collections import deque
import numpy as np
import pandas as pd
import torch
from torch import autograd, nn
import torch.nn.functional as F
from torch.distributions.beta import Beta
from utils.display_plt import display_plt
os.environ['KMP_DUPLICATE_LIB_OK'] = 'TRUE'
USE_CUDA = torch.cu... | 8,541 | 40.668293 | 121 | py |
Gym-ATC-Attack-Project | Gym-ATC-Attack-Project-main/attacks/st_attack_v2.py | import numpy as np
import torch
from torch import nn
from attacks.attack_v2 import Attack, Variable
class STAttack(Attack):
def __init__(self, env, device, agent_c, agent_g, load_path_c, load_path_g, epsilon, atk, attack_g, episodes,
method, beta):
super().__init__(env, device, agent_c, ... | 1,810 | 36.729167 | 115 | py |
Gym-ATC-Attack-Project | Gym-ATC-Attack-Project-main/attacks/st_attack_v1.py | import numpy as np
import torch
from torch import nn
from attacks.attack_v1 import Attack, Variable
class STAttack(Attack):
def __init__(self, env, device, agent, load_path, epsilon, atk, episodes, method, beta):
super().__init__(env, device, agent, load_path, epsilon, atk, episodes, method)
sel... | 1,511 | 36.8 | 93 | py |
Gym-ATC-Attack-Project | Gym-ATC-Attack-Project-main/attacks/main_v1.py | import random
import numpy as np
import torch
from attacks.attack_v1 import Attack
from attacks.st_attack_v1 import STAttack
from attacks.uni_attack_v1 import UniAttack
from envs.SimpleATC_env_global import SimpleEnv
from envs.SimpleATC_env_local import SimpleEnvLocal
from models.dqn_model import QNetwork, ResBlock
... | 2,392 | 38.229508 | 116 | py |
Gym-ATC-Attack-Project | Gym-ATC-Attack-Project-main/attacks/attack_v1.py | import os
from collections import deque
import numpy as np
import pandas as pd
import torch
from torch import autograd, nn
from torch.distributions.beta import Beta
import torch.nn.functional as F
from utils.display_plt import display_plt
os.environ['KMP_DUPLICATE_LIB_OK'] = 'TRUE'
USE_CUDA = torch.cuda.is_availabl... | 6,623 | 39.638037 | 121 | py |
Gym-ATC-Attack-Project | Gym-ATC-Attack-Project-main/attacks/uni_attack_v2.py | import torch
from torch import nn
from attacks.attack_v2 import Attack, Variable
class UniAttack(Attack):
def __init__(self, env, device, agent_c, agent_g, load_path_c, load_path_g, epsilon, atk, attack_g, episodes,
method, frq=1.0):
super().__init__(env, device, agent_c, agent_g, load_p... | 1,201 | 34.352941 | 115 | py |
Gym-ATC-Attack-Project | Gym-ATC-Attack-Project-main/models/dqn_model.py | import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
def fcLayer(input_units, output_units):
return nn.Linear(input_units, output_units)
class ResBlock(nn.Module):
'''
Residual block of batch norm and fc layers
'''
def __init__(self, input_units, output_units, d... | 2,850 | 29.655914 | 90 | py |
Gym-ATC-Attack-Project | Gym-ATC-Attack-Project-main/agents/dqn_simple_env.py | import datetime
import os
import random
from collections import deque
import numpy as np
import torch
from matplotlib import pyplot as plt
from agents.dqn_agent_simple_env import Agent
from envs.SimpleATC_env_global import SimpleEnv
from envs.SimpleATC_env_local import SimpleEnvLocal
from envs.SimpleATC_env_local_x i... | 6,114 | 33.548023 | 117 | py |
Gym-ATC-Attack-Project | Gym-ATC-Attack-Project-main/agents/dqn_agent_simple_env_v2.py | import random
from collections import deque, namedtuple
import numpy as np
import torch
from torch import optim
import torch.nn.functional as F
from models.dqn_model import QNetwork, ResBlock
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
BUFFER_SIZE = int(1e5)
BATCH_SIZE = 64
GAMMA = 0.99
... | 6,521 | 41.907895 | 120 | py |
Gym-ATC-Attack-Project | Gym-ATC-Attack-Project-main/agents/dqn_agent_simple_env.py | import random
from collections import deque, namedtuple
import numpy as np
import torch
from torch import optim
import torch.nn.functional as F
from models.dqn_model import QNetwork, ResBlock
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
BUFFER_SIZE = int(1e5)
BATCH_SIZE = 64
GAMMA = 0.99
... | 4,988 | 39.893443 | 120 | py |
Gym-ATC-Attack-Project | Gym-ATC-Attack-Project-main/agents/dqn_simple_env_v2.py | import datetime
import os
import random
from collections import deque
import numpy as np
import torch
from agents.dqn_agent_simple_env_v2 import Agent2
from envs.SimpleATC_env_global_v2 import SimpleEnvV2
from envs.SimpleATC_env_local_v2 import SimpleEnvLocalV2
from envs.SimpleATC_env_local_x_v2 import SimpleEnvLocal... | 7,054 | 38.194444 | 117 | py |
nn-sdp | nn-sdp-main/exts/simple_test.py | """
A simple example for bounding neural network outputs under input perturbations.
This example serves as a skeleton for robustness verification of neural networks.
"""
import os
import torch
import torch.nn as nn
import torchvision
from auto_LiRPA import BoundedModule, BoundedTensor
from auto_LiRPA.perturbations imp... | 5,037 | 46.528302 | 162 | py |
nn-sdp | nn-sdp-main/exts/auto_lirpa_bridge.py | import torch
import torch.nn as nn
import numpy as np
# pip install git+https://github.com/AntonXue/onnx2pytorch.git
import onnx2pytorch
import onnx
import auto_LiRPA
from auto_LiRPA.operators import *
from auto_LiRPA import BoundedModule, BoundedTensor, PerturbationLpNorm
import re
# Adapted from:
# https://github.co... | 4,966 | 36.916031 | 127 | py |
nn-sdp | nn-sdp-main/exts/auto_LiRPA/bounded_tensor.py | import torch
import torch.nn as nn
from torch import Tensor as Tensor
import torch._C as _C
class BoundedTensor(Tensor):
@staticmethod
# We need to override the __new__ method since Tensor is a C class
def __new__(cls, x, ptb, *args, **kwargs):
if isinstance(x, Tensor):
tensor = super... | 3,070 | 30.336735 | 95 | py |
nn-sdp | nn-sdp-main/exts/auto_LiRPA/adam_element_lr.py | import torch
import math
from torch.optim.optimizer import Optimizer
from torch import Tensor
from typing import List, Optional
def adam(params: List[Tensor],
grads: List[Tensor],
exp_avgs: List[Tensor],
exp_avg_sqs: List[Tensor],
max_exp_avg_sqs: List[Tensor],
state_steps... | 7,447 | 40.377778 | 120 | py |
nn-sdp | nn-sdp-main/exts/auto_LiRPA/bound_general.py | import time
import os
import numpy as np
from collections import OrderedDict, deque, defaultdict
import torch
import torch.optim as optim
from torch.nn import DataParallel, Parameter, parameter
from .bound_op_map import bound_op_map
from .bound_ops import *
from .bounded_tensor import BoundedTensor, BoundedParameter
... | 111,697 | 54.023645 | 275 | py |
nn-sdp | nn-sdp-main/exts/auto_LiRPA/wrapper.py | import torch
import torch.nn as nn
class CrossEntropyWrapper(nn.Module):
def __init__(self, model):
super(CrossEntropyWrapper, self).__init__()
self.model = model
def forward(self, x, labels):
y = self.model(x)
logits = y - torch.gather(y, dim=-1, index=labels.unsqueeze(-1))
... | 740 | 32.681818 | 72 | py |
nn-sdp | nn-sdp-main/exts/auto_LiRPA/parse_graph.py | import os
import torch
from collections import OrderedDict
import re
from collections import namedtuple
from torch.onnx import OperatorExportTypes
from packaging import version
from .bounded_tensor import BoundedTensor, BoundedParameter
from .utils import logger, unpack_inputs
Node = namedtuple('Node', (
'name', '... | 6,956 | 38.754286 | 124 | py |
nn-sdp | nn-sdp-main/exts/auto_LiRPA/utils.py | import logging
import pickle
import time
import torch
import torch.nn as nn
import os
import sys
import appdirs
from collections import defaultdict, Sequence, namedtuple
from functools import reduce
import operator
import math
import torch.nn.functional as F
import warnings
logging.basicConfig(
format='%(levelname... | 14,640 | 42.835329 | 330 | py |
nn-sdp | nn-sdp-main/exts/auto_LiRPA/perturbations.py | import os
import json
import math
import numpy as np
import torch
import torch.nn as nn
from .utils import logger, eyeC, LinearBound, Patches, BoundList, patches_to_matrix, inplace_unfold
import torch.nn.functional as F
class Perturbation:
r"""
Base class for a perturbation specification. Please see examples
... | 23,909 | 44.284091 | 159 | py |
nn-sdp | nn-sdp-main/exts/auto_LiRPA/operators/shape.py | """ Shape operators """
from .base import *
class BoundReshape(Bound):
def __init__(self, input_name, name, ori_name, attr, inputs, output_index, options, device):
super().__init__(input_name, name, ori_name, attr, inputs, output_index, options, device)
@Bound.save_io_shape
def forward(self, x, sh... | 22,058 | 38.111702 | 115 | py |
nn-sdp | nn-sdp-main/exts/auto_LiRPA/operators/base.py | """ Base class and functions for implementing bound operators"""
import copy
import os
import time
import math
import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
from itertools import chain
from numpy.lib.arraysetops import isin
from collections import OrderedDict
from auto_LiRPA.per... | 18,010 | 40.886047 | 140 | py |
nn-sdp | nn-sdp-main/exts/auto_LiRPA/operators/softmax.py | """ Softmax """
from .base import *
class BoundSoftmaxImpl(nn.Module):
def __init__(self, axis):
super().__init__()
self.axis = axis
assert self.axis == int(self.axis)
@Bound.save_io_shape
def forward(self, x):
max_x = torch.max(x, dim=self.axis).values
x = torch.ex... | 1,874 | 35.057692 | 97 | py |
nn-sdp | nn-sdp-main/exts/auto_LiRPA/operators/activation.py | """ Activation operators or other unary nonlinear operators"""
from .base import *
class BoundActivation(Bound):
def __init__(self, input_name, name, ori_name, attr, inputs, output_index, options, device):
super().__init__(input_name, name, ori_name, attr, inputs, output_index, options, device)
sel... | 66,873 | 53.236821 | 240 | py |
nn-sdp | nn-sdp-main/exts/auto_LiRPA/operators/constant.py | """ Constant operators, including operators that are usually fixed nodes and not perturbed """
from .base import *
class BoundConstant(Bound):
def __init__(self, input_name, name, ori_name, attr, inputs, output_index, options, device):
super().__init__(input_name, name, ori_name, attr, inputs, output_index... | 5,426 | 38.326087 | 124 | py |
nn-sdp | nn-sdp-main/exts/auto_LiRPA/operators/dtype.py | from .base import *
class BoundCast(Bound):
def __init__(self, input_name, name, ori_name, attr, inputs, output_index, options, device):
super().__init__(input_name, name, ori_name, attr, inputs, output_index, options, device)
self.to = attr['to']
self.data_types = [
None, tor... | 1,139 | 35.774194 | 97 | py |
nn-sdp | nn-sdp-main/exts/auto_LiRPA/operators/reduce.py | """ Reduce operators"""
from .base import *
class BoundReduceMax(Bound):
def __init__(self, input_name, name, ori_name, attr, inputs, output_index, options, device):
super().__init__(input_name, name, ori_name, attr, inputs, output_index, options, device)
self.axis = attr['axes']
# for tor... | 6,221 | 38.379747 | 127 | py |
nn-sdp | nn-sdp-main/exts/auto_LiRPA/operators/convolution.py | """ Convolution, pooling and padding operators"""
from .base import *
from .activation import BoundOptimizableActivation
class BoundConv(Bound):
def __init__(self, input_name, name, ori_name, attr, inputs, output_index, options, device):
assert (attr['pads'][0] == attr['pads'][2])
assert (attr['pa... | 29,100 | 53.091078 | 184 | py |
nn-sdp | nn-sdp-main/exts/auto_LiRPA/operators/linear.py | """ Linear (possibly with weight perturbation) or Dot product layers """
from .base import *
from .bivariate import BoundMul
class BoundLinear(Bound):
def __init__(self, input_name, name, ori_name, attr, inputs, output_index, options, device):
# Gemm:
# A = A if transA == 0 else A.T
# B = B... | 29,855 | 47.546341 | 157 | py |
nn-sdp | nn-sdp-main/exts/auto_LiRPA/operators/dropout.py | from .base import *
class BoundDropout(Bound):
def __init__(self, input_name, name, ori_name, attr, inputs, output_index, options, device):
super().__init__(input_name, name, ori_name, attr, inputs, output_index, options, device)
self.dropout = nn.Dropout(p=attr['ratio'])
self.scale = 1 / (... | 1,445 | 36.076923 | 103 | py |
nn-sdp | nn-sdp-main/exts/auto_LiRPA/operators/rnn.py | """ RNN """
from .base import *
class BoundRNN(Bound):
def __init__(self, input_name, name, ori_name, attr, inputs, output_index, options, device):
super().__init__(input_name, name, ori_name, attr, inputs, output_index, options, device)
self.complex = True
self.output_index = output_index... | 2,195 | 36.862069 | 97 | py |
nn-sdp | nn-sdp-main/exts/auto_LiRPA/operators/normalization.py | """ Normalization operators"""
from .base import *
class BoundBatchNormalization(Bound):
def __init__(self, input_name, name, ori_name, attr, inputs, output_index, options, device, training):
super().__init__(input_name, name, ori_name, attr, inputs, output_index, options, device)
self.eps = attr['... | 9,170 | 52.947059 | 170 | py |
nn-sdp | nn-sdp-main/exts/auto_LiRPA/operators/leaf.py | """ Leaf nodes (indepedent nodes in the auto_LiRPA paper),
including input, parameter, buffer, etc."""
from .base import *
class BoundInput(Bound):
def __init__(self, input_name, name, ori_name, value, perturbation=None):
super().__init__(input_name, name, ori_name)
self.value = value
self... | 8,101 | 43.032609 | 120 | py |
nn-sdp | nn-sdp-main/exts/auto_LiRPA/operators/logical.py | """ Logical operators"""
from .base import *
class BoundWhere(Bound):
def __init__(self, input_name, name, ori_name, attr, inputs, output_index, options, device):
super().__init__(input_name, name, ori_name, attr, inputs, output_index, options, device)
@Bound.save_io_shape
def forward(self, condi... | 2,040 | 36.109091 | 97 | py |
nn-sdp | nn-sdp-main/exts/auto_LiRPA/operators/bivariate.py | """ Bivariate operators"""
from .base import *
from .activation import BoundSqrt, BoundReciprocal
class BoundMul(Bound):
def __init__(self, input_name, name, ori_name, attr, inputs, output_index, options, device):
super().__init__(input_name, name, ori_name, attr, inputs, output_index, options, device)
... | 15,066 | 38.965517 | 120 | py |
nn-sdp | nn-sdp-main/exts/NNet/examples/keras2nnet.py | import numpy as np
import h5py
from keras.models import load_model
import theano.tensor as T
from NNet.utils.writeNNet import writeNNet
# Load Keras network saved using model.save()
kerasFile = "KerasTestNetwork.h5"
# The example network has a custom loss function, so it needs to be defined for this example
def asym... | 2,517 | 47.423077 | 123 | py |
Implicit-Group-Sparsity | Implicit-Group-Sparsity-main/src/model.py | import numpy as np
import torch
from sklearn.linear_model import Lasso
import matplotlib.pyplot as plt
import copy
from src.group_model import EarlyStopping
class sparseModel(torch.nn.Module):
def __init__(self, p=500, N=2, only_pos=True):
super().__init__()
self.p = p
self.N = N
s... | 2,930 | 33.081395 | 91 | py |
Implicit-Group-Sparsity | Implicit-Group-Sparsity-main/src/group_model.py | import torch
import numpy as np
import copy
import matplotlib.pyplot as plt
class GaussianSimulation:
def __init__(self, m=200, p=500, seed=42, support = np.repeat([1,2,3,4],4), # np.tile
std = 0.5):
self.m = m
self.p = p
self.k = support.shape[0]
self.support = sup... | 18,452 | 39.825221 | 152 | py |
IT-Defense | IT-Defense-main/it_defense.py | import torch.nn as nn
class Infer(nn.Module):
def __init__(self, model):
super(Infer, self).__init__()
self.model = model
for p in self.parameters():
p.requires_grad = False
def forward(self, x):
x.data = x[:, :, torch.randperm(x.size()[2])].data
x = self.mo... | 365 | 23.4 | 58 | py |
DualRec | DualRec-main/run.py | from argparse import ArgumentParser
import pytorch_lightning as pl
from pytorch_lightning.utilities.cli import LightningCLI
from src.model import DualRecModule as Module
from src.datamodule import DualRecDataModule as DataModule
def cli_main():
pl.seed_everything(42)
cli = LightningCLI(
Module, DataM... | 429 | 22.888889 | 79 | py |
DualRec | DualRec-main/src/utils.py | import torch
def recall(scores, labels, k):
scores = scores.cpu()
labels = labels.cpu()
rank = (-scores).argsort(dim=1)
cut = rank[:, :k]
hit = labels.gather(1, cut)
return (hit.sum(1).float() / labels.sum(1).float()).mean().item()
def ndcg(scores, labels, k):
scores = scores.cpu()
l... | 1,875 | 27 | 83 | py |
DualRec | DualRec-main/src/model.py | import torch
import torch.nn.functional as F
import pytorch_lightning as pl
from .models import DotProductPredictionHead
from .models.dualrec import DualRecModel
from .utils import recalls_and_ndcgs_for_ks, mrr
class DualRecModule(pl.LightningModule):
def __init__(
self,
dualrec: DualRecModel,
... | 6,948 | 37.821229 | 170 | py |
DualRec | DualRec-main/src/datamodule.py | import pytorch_lightning as pl
from .datasets import AbstractDataset
from .dataloaders import DualRecDataloader
class DualRecDataModule(pl.LightningDataModule):
def __init__(
self,
dataset_code: str = None,
data_type: str = None,
data_file_eval: str = None,
data_file_test: ... | 2,505 | 32.864865 | 84 | py |
DualRec | DualRec-main/src/models/dualrec.py | import torch
from torch import nn
import pytorch_lightning as pl
import numpy as np
import torch.nn.functional as F
import einops
# 1D conv compression function
class MultiheadAttention(pl.LightningModule):
def __init__(
self,
d_model: int = None,
d_head: int = None,
n_head: int = ... | 13,784 | 33.376559 | 117 | py |
DualRec | DualRec-main/src/models/heads.py | import torch
import torch.nn as nn
class LinearPredictionHead(nn.Module):
def __init__(self, args):
super().__init__()
self.vocab_size = args.num_items + 1
hidden = args.d_model
self.out = nn.Linear(hidden, self.vocab_size)
def forward(self, x, candidates=None):
x = se... | 1,128 | 31.257143 | 74 | py |
DualRec | DualRec-main/src/datasets/base.py | RAW_DATASET_ROOT_FOLDER = "Data"
import pandas as pd
from tqdm import tqdm
tqdm.pandas()
import os
from abc import *
from pathlib import Path
import pickle
from torch.utils.data import RandomSampler, SequentialSampler
from .utils import *
sequential_data_list = ["Beauty", "Sports_and_Outdoors", "Toys_and_Games", "Ye... | 3,985 | 32.216667 | 98 | py |
DualRec | DualRec-main/src/dataloaders/dualrec.py | from .base import AbstractDataloader
import torch
import numpy as np
import torch.utils.data as data_utils
class DualRecDataloader(AbstractDataloader):
def __init__(
self,
dataset,
data_type,
seg_len,
num_train_seg,
num_test_seg,
pred_prob,
num_work... | 6,598 | 29.270642 | 87 | py |
PercepTreeV1 | PercepTreeV1-main/train_synth_RGB.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
from __future__ import absolute_import
# Some basic setup:
# Setup detectron2 logger
from detectron2.utils.logger import setup_logger
setup_logger()
# import some common libraries
import torch; print(torch.__version__)
import os, json, cv2, random
import numpy as np
im... | 17,826 | 42.374696 | 183 | py |
PercepTreeV1 | PercepTreeV1-main/demo_single_frame.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Test trained network on a video
"""
from __future__ import absolute_import
# Setup detectron2 logger
from detectron2.utils.logger import setup_logger
setup_logger()
# import some common libraries
import os, cv2
import torch
# import detectron2 utilities
from detect... | 2,475 | 33.388889 | 139 | py |
PercepTreeV1 | PercepTreeV1-main/demo_video.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Test trained network on a video
"""
from __future__ import absolute_import
# Setup detectron2 logger
from detectron2.utils.logger import setup_logger
setup_logger()
# import some common libraries
import os, cv2
import torch
# import detectron2 utilities
from detect... | 4,050 | 33.922414 | 139 | py |
SGDD-TST | SGDD-TST-master/metric/all_metrics.py | from tqdm.auto import tqdm
import os
import sys
import pandas as pd
import numpy as np
import torch
from torch.utils.data import Dataset, DataLoader
from transformers import AutoModel, AutoTokenizer, AutoModelForSequenceClassification
import numpy as np
import gensim
from nltk import wordpunct_tokenize
from scipy.spati... | 9,256 | 37.570833 | 123 | py |
Real-time-Global-Inference-Network | Real-time-Global-Inference-Network-master/code/main.py | """
QNet: Main SetUp Code
Author: Arka Sadhu
"""
import pandas as pd
from dat_loader import get_data
from mdl import get_default_net
# from qnet_model import get_default_net
from loss import get_default_loss
import torch
import fire
from evaluator import Evaluator
# from evaluate import Evaluator
import json
from funct... | 4,654 | 31.326389 | 93 | py |
Real-time-Global-Inference-Network | Real-time-Global-Inference-Network-master/code/main_dist.py | """
Main file for distributed training
"""
from dat_loader import get_data
from mdl import get_default_net
from loss import get_default_loss
from evaluator import get_default_eval
from utils import Learner, synchronize
import numpy as np
import torch
import fire
from functools import partial
from extended_config impo... | 3,042 | 29.128713 | 75 | py |
Real-time-Global-Inference-Network | Real-time-Global-Inference-Network-master/code/mdl.py | """
Model file for zsgnet
Author: Arka Sadhu
"""
import torch
import torch.nn as nn
# import torch.nn.functional as F
import torchvision.models as tvm
from torch.nn.utils.rnn import pack_padded_sequence, pad_packed_sequence
from fpn_resnet import FPN_backbone
from anchors import create_grid
import ssd_vgg
from typing i... | 16,428 | 35.028509 | 134 | py |
Real-time-Global-Inference-Network | Real-time-Global-Inference-Network-master/code/anchors.py | """
Creates anchor based on the backbone
Based on code from https://github.com/fastai/fastai_docs/blob/master/dev_nb/102a_coco.ipynb
Author: Arka Sadhu
"""
import torch
import numpy as np
from torch import nn
def cthw2tlbr(boxes):
"Convert center/size format `boxes` to top/left bottom/right corners."
top_left... | 6,704 | 32.863636 | 91 | py |
Real-time-Global-Inference-Network | Real-time-Global-Inference-Network-master/code/dat_loader.py | from torch.utils.data import Dataset, DataLoader
from torch.utils.data.distributed import DistributedSampler
from torchvision.transforms import functional as F
import pandas as pd
from utils import DataWrap
import numpy as np
from pathlib import Path
import torch
from tqdm import tqdm
import re
import PIL
import json
f... | 12,266 | 36.861111 | 132 | py |
Real-time-Global-Inference-Network | Real-time-Global-Inference-Network-master/code/afs.py | import torch.nn as nn
import torch
import torch.utils.model_zoo as model_zoo
import torch.nn.functional as F
import numpy as np
class AdaptiveFeatureSelection(nn.Module):
''' AdaptiveFeatureSelection '''
def __init__(self, down_num,down_ins,up_num,up_ins,cur_in,lang_in,hiddens,outs):
super().__init__(... | 2,527 | 36.731343 | 125 | py |
Real-time-Global-Inference-Network | Real-time-Global-Inference-Network-master/code/loss.py | import torch
from torch import nn
import torch.nn.functional as F
from anchors import (create_anchors, simple_match_anchors,
bbox_to_reg_params, IoU_values,tlbr2cthw)
from typing import Dict
from functools import partial
# from utils import reduce_dict
class ZSGLoss(nn.Module):
"""
Criter... | 5,838 | 33.550296 | 161 | py |
Real-time-Global-Inference-Network | Real-time-Global-Inference-Network-master/code/utils.py | """
Utility functions
"""
from typing import Dict, List, Optional, Union, Any, Callable
import torch
from torch import nn
from torch.utils.data import DataLoader
from dataclasses import dataclass
from pathlib import Path
import sys
import re
import numpy as np
from collections import Counter
from tqdm import tqdm
impor... | 24,235 | 33.183357 | 115 | py |
Real-time-Global-Inference-Network | Real-time-Global-Inference-Network-master/code/ssd_vgg.py | """
Adapted from the amazing repository: https://github.com/amdegroot/ssd.pytorch/blob/master/ssd.py
"""
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Variable
import torchvision.models as tvm
import os
class SSD(nn.Module):
"""Single Shot Multibox Architecture
... | 7,400 | 35.820896 | 96 | py |
Real-time-Global-Inference-Network | Real-time-Global-Inference-Network-master/code/evaluator.py | import torch
from torch import nn
from anchors import (create_anchors, reg_params_to_bbox,
IoU_values, x1y1x2y2_to_y1x1y2x2)
from typing import Dict
from functools import partial
# from utils import reduce_dict
def reshape(box, new_size):
"""
box: (N, 4) in y1x1y2x2 format
new_size: (... | 3,796 | 30.122951 | 74 | py |
Real-time-Global-Inference-Network | Real-time-Global-Inference-Network-master/code/fpn_resnet.py | """
Taken from the wonderful repository: https://github.com/yhenon/pytorch-retinanet/blob/master/model.py
"""
import torch.nn as nn
import torch
import torch.utils.model_zoo as model_zoo
import torch.nn.functional as F
import numpy as np
model_urls = {
'resnet18': 'https://download.pytorch.org/models/resnet18-5c1... | 11,429 | 34.06135 | 149 | py |
Real-time-Global-Inference-Network | Real-time-Global-Inference-Network-master/code/garan.py | import torch.nn as nn
import torch
import torch.utils.model_zoo as model_zoo
import torch.nn.functional as F
import numpy as np
class CollectDiffuseAttention(nn.Module):
''' CollectDiffuseAttention '''
def __init__(self, temperature, attn_dropout=0.1):
super().__init__()
self.temperature = temp... | 3,676 | 35.04902 | 96 | py |
Real-time-Global-Inference-Network | Real-time-Global-Inference-Network-master/code/eval_script.py | """
Simple evaluation script.
Requires outputs to be saved before in the following format
[
{
"id": , "pred_boxes": (x1y1x2y2), "pred_scores": int
}
]
"""
from anchors import IoU_values
import pickle
import pandas as pd
import ast
import torch
import fire
from pathlib import Path
def evaluate(pred_fil... | 1,749 | 27.688525 | 78 | py |
Real-time-Global-Inference-Network | Real-time-Global-Inference-Network-master/data/flatten_train.py | """
Converts input csv file of type: img_name, bbox, List[queries]
to output csv file of type: img_name, bbox, query
"""
import fire
import pandas as pd
from tqdm import tqdm
import copy
import ast
def converter(inp_csv, out_csv):
inp_df = pd.read_csv(inp_csv)
inp_df['query'] = inp_df['query'].apply(
... | 1,088 | 31.029412 | 161 | py |
cp-vton | cp-vton-master/visualization.py | from tensorboardX import SummaryWriter
import torch
from PIL import Image
import os
def tensor_for_board(img_tensor):
# map into [0,1]
tensor = (img_tensor.clone()+1) * 0.5
tensor.cpu().clamp(0,1)
if tensor.size(1) == 1:
tensor = tensor.repeat(1,3,1,1)
return tensor
def tensor_list_for_b... | 1,969 | 32.389831 | 97 | py |
cp-vton | cp-vton-master/test.py | #coding=utf-8
import torch
import torch.nn as nn
import torch.nn.functional as F
import argparse
import os
import time
from cp_dataset import CPDataset, CPDataLoader
from networks import GMM, UnetGenerator, load_checkpoint
from tensorboardX import SummaryWriter
from visualization import board_add_image, board_add_ima... | 6,109 | 36.256098 | 108 | py |
cp-vton | cp-vton-master/cp_dataset.py | #coding=utf-8
import torch
import torch.utils.data as data
import torchvision.transforms as transforms
from PIL import Image
from PIL import ImageDraw
import os.path as osp
import numpy as np
import json
class CPDataset(data.Dataset):
"""Dataset for CP-VTON.
"""
def __init__(self, opt):
super(CPD... | 7,658 | 37.104478 | 101 | py |
cp-vton | cp-vton-master/networks.py | #coding=utf-8
import torch
import torch.nn as nn
from torch.nn import init
from torchvision import models
import os
import numpy as np
def weights_init_normal(m):
classname = m.__class__.__name__
if classname.find('Conv') != -1:
init.normal_(m.weight.data, 0.0, 0.02)
elif classname.find('Linear') ... | 18,703 | 41.605923 | 151 | py |
cp-vton | cp-vton-master/train.py | #coding=utf-8
import torch
import torch.nn as nn
import torch.nn.functional as F
import argparse
import os
import time
from cp_dataset import CPDataset, CPDataLoader
from networks import GMM, UnetGenerator, VGGLoss, load_checkpoint, save_checkpoint
from tensorboardX import SummaryWriter
from visualization import boar... | 7,657 | 38.885417 | 108 | py |
integral-human-pose | integral-human-pose-master/common/utility/image_processing_cv.py | import numpy as np
import cv2
import torch
import matplotlib.pyplot as plt
# from mpl_toolkits.mplot3d import axes3d, Axes3D # <-- Note the capitalization!
from common.utility.visualization import cv_draw_joints, plot_3d_skeleton
from common.utility.augment import do_augmentation
from common.utility.utils import cal... | 9,048 | 38.00431 | 119 | py |
integral-human-pose | integral-human-pose-master/pytorch_projects/hm36_challenge/test.py | import os
import pprint
import copy
import time
import logging
# define project dependency
import _init_paths
# pytorch
import torch
from torch.utils.data import DataLoader
# import from common_pytorch
# from common_pytorch.dataset.__init__ import *
from common_pytorch.dataset.all_dataset import *
from common_pytor... | 5,388 | 44.285714 | 119 | py |
integral-human-pose | integral-human-pose-master/pytorch_projects/hm36_challenge/_init_paths.py | import os
import sys
def add_path(path):
if path not in sys.path:
sys.path.insert(0, path)
this_dir = os.path.dirname(__file__)
add_path(os.path.join(this_dir, '..', '..', 'common'))
add_path(os.path.join(this_dir, '..', 'common_pytorch'))
add_path(os.path.join(this_dir, '..', '..'))
add_path(os.path.join... | 516 | 26.210526 | 56 | py |
integral-human-pose | integral-human-pose-master/pytorch_projects/hm36_challenge/train.py | import os
import pprint
import shutil
import copy
import time
import matplotlib
matplotlib.use('Agg')
# define project dependency
import _init_paths
# common
from common.speedometer import Speedometer
from common.tensorboard import TensorboardCallback
from common.utility.logger import create_logger
from common.utilit... | 8,812 | 46.637838 | 118 | py |
integral-human-pose | integral-human-pose-master/pytorch_projects/hm36_challenge/core/loader.py | import numpy as np
import torch.utils.data as data
from common.utility.image_processing_cv import get_single_patch_sample
from common_pytorch.dataset.hm36 import from_mpii_to_hm36, from_coco_to_hm36
class single_patch_Dataset(data.Dataset):
def __init__(self, db, is_train, det_bbox_src, patch_width, patch_heigh... | 9,401 | 39.878261 | 120 | py |
integral-human-pose | integral-human-pose-master/pytorch_projects/common_pytorch/io_pytorch.py | import torch
def save_model(state, model_prefix, logger, epoch):
file_path = '{}_epoch{}.pth.tar'.format(model_prefix, str(epoch))
torch.save(state, file_path)
logger.info("Write Model into {}".format(file_path))
def save_latest_model(state, model_prefix, logger):
'''
Save a latest ckpt to automat... | 786 | 30.48 | 69 | py |
integral-human-pose | integral-human-pose-master/pytorch_projects/common_pytorch/net_modules.py | import os
import torch
import logging
import numpy as np
import pickle
from common.speedometer import BatchEndParam
from common.utility.image_processing_cv import trans_coords_from_patch_to_org_3d
from common.utility.image_processing_cv import rescale_pose_from_patch_to_camera
from torch.nn.parallel.scatter_gather im... | 7,310 | 33.649289 | 118 | py |
integral-human-pose | integral-human-pose-master/pytorch_projects/common_pytorch/config_pytorch.py | import os
import yaml
import argparse
import copy
import numpy as np
from easydict import EasyDict as edict
def str2bool(v):
if v.lower() in ('yes', 'true', 't', 'y', '1'):
return True
elif v.lower() in ('no', 'false', 'f', 'n', '0'):
return False
else:
raise argparse.ArgumentTypeEr... | 5,351 | 34.443709 | 104 | py |
integral-human-pose | integral-human-pose-master/pytorch_projects/common_pytorch/optimizer.py | import torch.optim
def get_optimizer(config, network):
if config.optimizer_name == 'adam':
optimizer = torch.optim.Adam(network.parameters(), lr=config.lr)
elif config.optimizer_name == 'sgd':
optimizer = torch.optim.SGD(network.parameters(), lr=config.lr, momentum=config.momentum, weight_decay... | 720 | 47.066667 | 122 | py |
integral-human-pose | integral-human-pose-master/pytorch_projects/common_pytorch/base_modules/resnet.py | import torch.nn as nn
from torchvision.models.resnet import BasicBlock, Bottleneck
# Specification
resnet_spec = {18: (BasicBlock, [2, 2, 2, 2], [64, 64, 128, 256, 512], 'resnet18'),
34: (BasicBlock, [3, 4, 6, 3], [64, 64, 128, 256, 512], 'resnet34'),
50: (Bottleneck, [3, 4, 6, 3], [64, 2... | 2,549 | 40.129032 | 89 | py |
integral-human-pose | integral-human-pose-master/pytorch_projects/common_pytorch/base_modules/deconv_head.py | import torch.nn as nn
class DeconvHead(nn.Module):
def __init__(self, in_channels, num_layers, num_filters, kernel_size, conv_kernel_size, num_joints, depth_dim,
with_bias_end=True):
super(DeconvHead, self).__init__()
conv_num_filters = num_joints * depth_dim
assert kerne... | 2,300 | 39.368421 | 114 | py |
integral-human-pose | integral-human-pose-master/pytorch_projects/common_pytorch/base_modules/avg_pool_head.py | import torch.nn as nn
class AvgPoolHead(nn.Module):
def __init__(self, in_channels, out_channels, fea_map_size):
super(AvgPoolHead, self).__init__()
self.avgpool = nn.AvgPool2d(fea_map_size, stride=1)
self.fc = nn.Linear(in_channels, out_channels)
def forward(self, x):
x = self... | 405 | 30.230769 | 64 | py |
integral-human-pose | integral-human-pose-master/pytorch_projects/common_pytorch/blocks/resnet_direct_regression.py | import os
from easydict import EasyDict as edict
import torch
import torch.nn as nn
from torchvision.models.resnet import model_zoo, model_urls
from common_pytorch.base_modules.resnet import resnet_spec, ResNetBackbone
from common_pytorch.base_modules.avg_pool_head import AvgPoolHead
def get_default_network_config(... | 1,780 | 31.381818 | 100 | py |
integral-human-pose | integral-human-pose-master/pytorch_projects/common_pytorch/blocks/resnet_pose.py | import os
from easydict import EasyDict as edict
import torch
import torch.nn as nn
from torchvision.models.resnet import model_zoo, model_urls
from common_pytorch.base_modules.resnet import resnet_spec, ResNetBackbone
from common_pytorch.base_modules.deconv_head import DeconvHead
def get_default_network_config():
... | 2,012 | 32 | 109 | py |
integral-human-pose | integral-human-pose-master/pytorch_projects/common_pytorch/common_loss/loss_recorder.py | import torch
class LossRecorder(object):
def __init__(self):
self.sum = 0
self.count = 0.0000001
def update(self, val, n=1):
self.sum += val * n
self.count += n
def get_avg(self):
mean_val = self.sum / self.count
if isinstance(mean_val, torch.Tensor):
... | 544 | 22.695652 | 48 | py |
integral-human-pose | integral-human-pose-master/pytorch_projects/common_pytorch/common_loss/integral.py | import torch
from torch.nn import functional as F
def generate_3d_integral_preds_tensor(heatmaps, num_joints, x_dim, y_dim, z_dim):
assert isinstance(heatmaps, torch.Tensor)
heatmaps = heatmaps.reshape((heatmaps.shape[0], num_joints, z_dim, y_dim, x_dim))
accu_x = heatmaps.sum(dim=2)
accu_x = accu_x... | 1,689 | 37.409091 | 131 | py |
integral-human-pose | integral-human-pose-master/pytorch_projects/common_pytorch/common_loss/weighted_mse.py | import torch
def weighted_mse_loss(input, target, weights, size_average):
out = (input - target) ** 2
out = out * weights
if size_average:
return out.sum() / len(input)
else:
return out.sum()
def weighted_l1_loss(input, target, weights, size_average):
out = torch.abs(input - target... | 440 | 23.5 | 60 | py |
integral-human-pose | integral-human-pose-master/pytorch_projects/common_pytorch/common_loss/balanced_parallel.py | """Encoding Data Parallel"""
import threading
import functools
import torch
from torch.autograd import Variable, Function
import torch.cuda.comm as comm
from torch.nn.parallel.data_parallel import DataParallel
from torch.nn.parallel.parallel_apply import get_a_var
from torch.nn.parallel._functions import ReduceAddCoale... | 9,056 | 36.42562 | 144 | py |
integral-human-pose | integral-human-pose-master/pytorch_projects/common_pytorch/loss/joint_location.py | import numpy as np
from easydict import EasyDict as edict
import torch.nn as nn
from common_pytorch.common_loss.weighted_mse import weighted_l1_loss, weighted_mse_loss
# config
def get_default_loss_config():
config = edict()
config.loss_type = 'L2'
return config
# config
# define loss
def _assert_no_... | 3,012 | 26.390909 | 89 | py |
integral-human-pose | integral-human-pose-master/pytorch_projects/common_pytorch/loss/integral.py | import numpy as np
from easydict import EasyDict as edict
import torch.nn as nn
from common_pytorch.common_loss.weighted_mse import weighted_l1_loss, weighted_mse_loss
from common_pytorch.common_loss.integral import softmax_integral_tensor
# config
def get_default_loss_config():
config = edict()
config.loss... | 4,377 | 28.782313 | 108 | py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.