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 |
|---|---|---|---|---|---|---|
arf_paper | arf_paper-master/generative_benchmark/5.3_Runtime/runtime_main.py | import time
import pandas as pd
import numpy as np
from sdgym.datasets import load_dataset
from sdgym.datasets import load_tables
from sklearn.utils import resample
import rpy2
import rpy2.robjects as robjects
import rpy2.robjects.packages as rpackages
from rpy2.robjects import pandas2ri
pandas2ri.activate()
r = robjec... | 4,900 | 36.7 | 134 | py |
arf_paper | arf_paper-master/appx_mnist/mnist28_visual.py | import pandas as pd
import numpy as np
import random
import torch
from sdv.tabular import CTGAN, TVAE
from cDCGAN import cDCGAN
import matplotlib.pyplot as plt
import rpy2.robjects as robjects
import rpy2.robjects.packages as rpackages
from rpy2.robjects import pandas2ri
r = robjects.r
base = rpackages.importr('base'... | 3,075 | 28.576923 | 101 | py |
arf_paper | arf_paper-master/appx_mnist/cDCGAN.py | #Standard cDCGAN
import numpy as np
import pandas as pd
import random
import torch
import torch.nn as nn
class Discriminator(nn.Module):
def __init__(self):
super(Discriminator, self).__init__()
# image input , input size : (batch_size, 1, 28, 28)
self.layer_x = nn.Sequential(n... | 14,576 | 44.553125 | 132 | py |
MVAug | MVAug-main/evaluation.py | import argparse
import os
import sys
import time
import warnings
from collections import defaultdict
from ctypes import c_bool
from multiprocessing import Queue
from pathlib import Path
import numpy as np
import torch
from configs.arguments import get_config_dict
from dataset import factory as data_factory
from loss ... | 15,998 | 44.451705 | 347 | py |
MVAug | MVAug-main/train.py | import os
import psutil
import time
import warnings
import torch
import torch.optim as optim
from torch.utils.tensorboard import SummaryWriter
from torch.optim.lr_scheduler import MultiStepLR
from configs.arguments import get_config_dict
from dataset import factory as data_factory
from evaluation import Evaluator
fr... | 5,952 | 37.908497 | 195 | py |
MVAug | MVAug-main/dataset/heatmapbuilder.py | import cv2
import numpy as np
import torch
from scipy.ndimage.filters import gaussian_filter
def gaussian_density_heatmap(size, points, radius):
points = np.array(points)
hm = np.zeros(size)
if points.shape[0] != 0:
hm[points[:,1],points[:,0]] = 1
hm = gaussian_filter(hm, radiu... | 2,018 | 24.884615 | 90 | py |
MVAug | MVAug-main/dataset/basedataset.py | import random
import numpy as np
import torch
from torchvision import transforms
from augmentation.homographyaugmentation import HomographyDataAugmentation
from dataset.utils import aggregate_multi_view_gt_points, generate_scene_roi_from_view_rois, generate_mask_from_polygon_perimeter, get_augmentation
from misc imp... | 8,615 | 42.736041 | 283 | py |
MVAug | MVAug-main/dataset/utils.py | import os
import time
import cv2
import json
import numpy as np
import PIL
import torch
from collections import namedtuple, defaultdict
from scipy.spatial.distance import cdist
from shapely.geometry import Polygon
from shapely.ops import unary_union
from skimage.draw import polygon, polygon_perimeter
from torchvisi... | 19,496 | 35.996205 | 154 | py |
MVAug | MVAug-main/dataset/factory.py | from torch.utils.data import DataLoader, Subset
from configs.pathes import conf_path
from misc.log_utils import log, dict_to_string
from dataset import wildtrack, multiviewX
from dataset import heatmapbuilder
from dataset.basedataset import FlowSceneSet
from dataset.utils import get_train_val_split_index
wildtrack_c... | 3,664 | 36.397959 | 119 | py |
MVAug | MVAug-main/misc/utils.py | import collections
import gc
import glob
import os
import sys
import numpy as np
import torch
from pathlib import Path
from misc.log_utils import log
if sys.version_info >= (3, 7):
class NpArray:
def __class_getitem__(self, arg):
pass
else:
# 3.6 and below don't support __class_getitem__
... | 6,653 | 32.437186 | 209 | py |
MVAug | MVAug-main/misc/geometry.py | import cv2
import numpy as np
import torch
from scipy.interpolate import interp1d
from skimage.draw import polygon, polygon_perimeter
from sympy.geometry.util import intersection, convex_hull
from sympy import Point, Polygon
from misc.log_utils import log
def project_to_ground_plane_pytorch(img, H, homography_input... | 14,537 | 34.545232 | 174 | py |
MVAug | MVAug-main/misc/pipeline.py | import time
import torch
from misc.log_utils import log
class MultiViewPipeline(torch.nn.Module):
def __init__(self, people_flow, object_tracker, flow_consistency):
super(MultiViewPipeline, self).__init__()
self.people_flow = people_flow
def forward(self, input_data):
time_stat = d... | 628 | 22.296296 | 70 | py |
MVAug | MVAug-main/misc/metric.py | import os
import motmetrics as mm
import numpy as np
import pandas as pd
import torch
from collections import defaultdict, Counter
from scipy.spatial.distance import cdist
from scipy.optimize import linear_sum_assignment
from sklearn.cluster import KMeans
from dataset.utils import generate_flow
from misc.log_utils... | 14,125 | 31.851163 | 247 | py |
MVAug | MVAug-main/misc/detection.py | import numpy as np
import torch
from sklearn.cluster import KMeans
def _nms(heatmap, kernel):
pad = (kernel - 1) // 2
#normalize heatmap such that it has a min of 0
heatmap_min = heatmap.min()
heatmap = heatmap - heatmap_min
hmax = torch.nn.functional.max_pool2d(heatmap, (kernel, kerne... | 2,154 | 30.691176 | 101 | py |
MVAug | MVAug-main/loss/loss.py | import torch
from misc.log_utils import log
class MSEwithROILoss(torch.nn.Module):
def __init__(self):
super(MSEwithROILoss, self).__init__()
self.mse = torch.nn.MSELoss(reduction="none")
def forward(self, pred, target, roi_mask=None):
loss = self.mse(pred, target)
if roi_m... | 2,847 | 26.384615 | 162 | py |
MVAug | MVAug-main/augmentation/homographyaugmentation.py |
import numpy as np
import torch
import torchvision
import augmentation.alignedaugmentation as alaug
from dataset.utils import is_in_frame
from misc import geometry
class HomographyDataAugmentation(torch.nn.Module):
"""
Data augmentation for image, gt, homography structure, which is reapeatable can be applie... | 4,130 | 45.41573 | 288 | py |
MVAug | MVAug-main/augmentation/reapeatabletransform.py | import torch
from contextlib import contextmanager
class RepeatableTransform(torch.nn.Module):
"""
Every forward call will applpy the same transform until reset is call,
after which the parameter of the transofrm are randomly replaced.
"""
def __init__(self, transform):
super().__init__()... | 2,148 | 31.560606 | 106 | py |
MVAug | MVAug-main/augmentation/alignedaugmentation.py | import math
import torch
from torchvision.transforms.functional import _get_perspective_coeffs, vflip, hflip
from augmentation.reapeatabletransform import RepeatableTransform
class AlignedResizedCropTransform(RepeatableTransform):
def __init__(self, resized_crop):
super().__init__(resized_crop)
... | 4,294 | 28.826389 | 83 | py |
MVAug | MVAug-main/model/multimodel.py | import torch
from torch.nn import functional as F
from torchvision import models
from misc.log_utils import log
from misc.geometry import project_to_ground_plane_pytorch
class MultiNet(torch.nn.Module):
def __init__(self, hm_size, homography_input_size, homography_output_size, nb_ch_out, model_image_pred=False... | 5,189 | 37.731343 | 180 | py |
MVAug | MVAug-main/model/multiviewmodel.py | import cv2
import numpy as np
import torch
from misc.log_utils import log
from model.multimodel import MultiNet
class MultiviewModel(torch.nn.Module):
def __init__(self, model_spec, data_spec):
super().__init__()
self.nb_hm = 1
# self.ground_hm_size = data_spec["hm_size"]#
s... | 1,829 | 27.59375 | 137 | py |
MVAug | MVAug-main/model/utils.py | import torch
from torch.cuda.amp import custom_bwd, custom_fwd
from misc.log_utils import log
def _sigmoid(x):
y = torch.clamp(torch.sigmoid(x), min=1e-4, max=1-1e-4)
return y
def shifted_sigmo(x):
y = 1.0 / (1.0 + torch.exp(-(x*6-3)))
return y
| 262 | 14.470588 | 57 | py |
MVAug | MVAug-main/model/pipeline.py | import time
import torch
from misc.log_utils import log
from misc.utils import PinnableDict
class MultiViewPipeline(torch.nn.Module):
def __init__(self, multiview_model):
super(MultiViewPipeline, self).__init__()
self.multiview_model = multiview_model
def forward(self, input_data):
... | 665 | 21.965517 | 67 | py |
SGP | SGP-main/ImageClassification/main_sgp_cifar_superclass.py | import torch
import torch.optim as optim
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Variable
import torchvision
from torchvision import datasets, transforms
import os
import os.path
from collections import OrderedDict
import matplotlib.pyplot as plt
import numpy as np
import ra... | 21,348 | 40.134875 | 163 | py |
SGP | SGP-main/ImageClassification/main_sgp_cifar100.py | import torch
import torch.optim as optim
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Variable
import torchvision
from torchvision import datasets, transforms
import os
import os.path
from collections import OrderedDict
import matplotlib.pyplot as plt
import numpy as np
import ra... | 20,563 | 39.08577 | 163 | py |
SGP | SGP-main/ImageClassification/dataloader/cifar100.py | import os,sys
import numpy as np
import torch
# import utils
from torchvision import datasets,transforms
from sklearn.utils import shuffle
cf100_dir = './data/'
file_dir = './data/binary_cifar100'
def get(seed=0,pc_valid=0.10):
data={}
taskcla=[]
size=[3,32,32]
if not os.path.isdir(file_dir):
... | 3,609 | 40.022727 | 159 | py |
SGP | SGP-main/ImageClassification/dataloader/cifar100_superclass.py | import os,sys
import numpy as np
import torch
# import utils
from torchvision import datasets,transforms
from sklearn.utils import shuffle
import scipy.io as sio
import pdb
import pickle
import random
import matplotlib.pyplot as plt
def cifar100_superclass_python(task_order, group=5, validation=False, val_ratio=0.05,... | 8,912 | 49.355932 | 123 | py |
SGP | SGP-main/RL_Experiments/arguments_rl.py | import argparse
import torch
def get_args():
parser = argparse.ArgumentParser(description='RL')
parser.add_argument(
'--algo', default='ppo', help='algorithm to use: a2c | ppo | acktr')
parser.add_argument('--approach', default='blip', type=str, required=True,
choices=['fine-t... | 8,306 | 30.95 | 109 | py |
SGP | SGP-main/RL_Experiments/main_gpm_rl.py | ''' Modified from Reference: https://github.com/Yujun-Shi/BLIP '''
import sys, os, time
import numpy as np
import torch.nn as nn
import torch.nn.init as init
import torch.nn.functional as F
import torch.optim as optim
import pickle
import torch
from arguments_rl import get_args
from collections import deque
from rl_m... | 9,654 | 36.714844 | 142 | py |
SGP | SGP-main/RL_Experiments/main_rl.py | ''' Reference: https://github.com/Yujun-Shi/BLIP '''
import sys, os, time
import numpy as np
import torch.nn as nn
import torch.nn.init as init
import torch.nn.functional as F
import torch.optim as optim
import pickle
import torch
from arguments_rl import get_args
from collections import deque
from rl_module.a2c_ppo... | 6,889 | 35.455026 | 128 | py |
SGP | SGP-main/RL_Experiments/utils.py | import os,sys
import numpy as np
import random
from copy import deepcopy
import math
import torch
import torch.nn as nn
from torch.optim import Optimizer
from tqdm import tqdm
from torch._six import inf
import pandas as pd
from PIL import Image
from sklearn.feature_extraction import image
import torchvision.transforms.... | 14,514 | 35.2875 | 120 | py |
SGP | SGP-main/RL_Experiments/rl_module/ppo_ewc.py | ''' Reference: https://github.com/Yujun-Shi/BLIP '''
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
import pdb
class PPO_EWC():
def __init__(self,
actor_critic,
clip_param,
ppo_epoch,
num_mini_batch,... | 13,542 | 44.753378 | 136 | py |
SGP | SGP-main/RL_Experiments/rl_module/quant_layer.py | import math
import torch
import torch.nn as nn
from torch.nn.parameter import Parameter
import torch.nn.functional as F
def uniform_quantize(bit_alloc, upper_bound):
class qfn(torch.autograd.Function):
@staticmethod
def forward(ctx, input):
# normalize to (-1, 1)
input = in... | 12,458 | 46.735632 | 116 | py |
SGP | SGP-main/RL_Experiments/rl_module/ppo_gpm_model.py | import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from .a2c_ppo_acktr.distributions import Bernoulli, Categorical, DiagGaussian
from .a2c_ppo_acktr.utils import init, init_weight
# quant layer specific
from .quant_layer import Conv2d_Q, Linear_Q
import pdb
from copy import deepcopy... | 15,494 | 33.742152 | 94 | py |
SGP | SGP-main/RL_Experiments/rl_module/train_ppo.py | import os
import time
from tqdm import tqdm
import numpy as np
import scipy.io as sio
import torch
from .a2c_ppo_acktr import utils
from .evaluation import evaluate
def train_ppo(actor_critic, agent, rollouts, task_idx, env_name, task_sequences, envs, obs_shape, args,
episode_rewards, tr_reward_arr, te... | 5,320 | 44.87069 | 149 | py |
SGP | SGP-main/RL_Experiments/rl_module/ppo.py | ''' Reference: https://github.com/Yujun-Shi/BLIP '''
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
class PPO():
def __init__(self,
actor_critic,
clip_param,
ppo_epoch,
num_mini_batch,
... | 4,110 | 38.152381 | 102 | py |
SGP | SGP-main/RL_Experiments/rl_module/ppo_blip.py | ''' Reference: https://github.com/Yujun-Shi/BLIP '''
import math
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from .quant_layer import Conv2d_Q, Linear_Q
from .ppo_blip_utils import update_fisher_exact
class PPO_BLIP():
def __init__(self,
actor_cr... | 7,091 | 38.4 | 95 | py |
SGP | SGP-main/RL_Experiments/rl_module/ppo_model.py | import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from .a2c_ppo_acktr.distributions import Bernoulli, Categorical, DiagGaussian
from .a2c_ppo_acktr.utils import init
# quant layer specific
from .quant_layer import Conv2d_Q, Linear_Q
class Flatten(nn.Module):
def forward(self, ... | 12,339 | 32.901099 | 88 | py |
SGP | SGP-main/RL_Experiments/rl_module/ppo_sgp.py | import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
import pdb
import math
import numpy as np
import matplotlib.pyplot as plt
from .adam_custom import adam_optim, adam_optim_bias
def compute_conv_output_size(Lin,kernel_size,stride=1,padding=0,dilation=1):
#Lin: input map ... | 15,125 | 43.357771 | 158 | py |
SGP | SGP-main/RL_Experiments/rl_module/ppo_blip_utils.py | import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.distributions.categorical import Categorical
from .quant_layer import Linear_Q, Conv2d_Q
__all__ = ['update_fisher_exact']
def batch_conv(x, weight, bias=None, stride=1, padding=0, dilation=1, groups=1):
if bias is N... | 4,170 | 38.72381 | 99 | py |
SGP | SGP-main/RL_Experiments/rl_module/evaluation.py | import numpy as np
import torch
from collections import deque
from .a2c_ppo_acktr import utils
from .a2c_ppo_acktr.envs import make_vec_envs
def evaluate(actor_critic, ob_rms, task_sequences, seed, num_processes, eval_log_dir,
device, obs_shape, current_task_idx, gamma):
eval_episode_rewards_arr = []... | 2,692 | 39.19403 | 106 | py |
SGP | SGP-main/RL_Experiments/rl_module/ppo_gpm_model_with_bias.py | import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from .a2c_ppo_acktr.distributions import Bernoulli, Categorical, DiagGaussian
from .a2c_ppo_acktr.utils import init, init_weight
# quant layer specific
from .quant_layer import Conv2d_Q, Linear_Q
import pdb
from copy import deepcopy... | 15,539 | 33.843049 | 94 | py |
SGP | SGP-main/RL_Experiments/rl_module/adam_custom.py | import numpy as np
import torch
from collections import OrderedDict
import math
class adam_optim:
def __init__(self, model, lr, eps, device):
self.m = OrderedDict()
self.v = OrderedDict()
self.beta_1=0.9 * torch.ones(1).to(device)
self.beta_2=0.999 * torch.ones(1).to(device)
... | 5,259 | 48.622642 | 115 | py |
SGP | SGP-main/RL_Experiments/rl_module/ppo_gpm.py | import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
import pdb
import math
import numpy as np
from .adam_custom import adam_optim, adam_optim_bias
def compute_conv_output_size(Lin,kernel_size,stride=1,padding=0,dilation=1):
#Lin: input map size , output: output map_size
... | 13,024 | 40.613419 | 158 | py |
SGP | SGP-main/RL_Experiments/rl_module/a2c_ppo_acktr/distributions.py | import math
import torch
import torch.nn as nn
import torch.nn.functional as F
from .utils import AddBias, init
"""
Modify standard PyTorch distributions so they are compatible with this code.
"""
#
# Standardize distribution interfaces
#
# Categorical
class FixedCategorical(torch.distributions.Categorical):
d... | 2,795 | 24.418182 | 86 | py |
SGP | SGP-main/RL_Experiments/rl_module/a2c_ppo_acktr/storage.py | import torch
from torch.utils.data.sampler import BatchSampler, SubsetRandomSampler
def _flatten_helper(T, N, _tensor):
return _tensor.view(T * N, *_tensor.size()[2:])
class RolloutStorage(object):
def __init__(self, num_steps, num_processes, obs_shape, action_space,
recurrent_hidden_state_... | 9,875 | 47.411765 | 103 | py |
SGP | SGP-main/RL_Experiments/rl_module/a2c_ppo_acktr/envs.py | import os
import gym
import numpy as np
import torch
from gym.spaces.box import Box
from gym.wrappers.clip_action import ClipAction
from stable_baselines3.common.atari_wrappers import (ClipRewardEnv,
EpisodicLifeEnv,
... | 8,403 | 31.199234 | 93 | py |
SGP | SGP-main/RL_Experiments/rl_module/a2c_ppo_acktr/utils.py | import glob
import os
import torch
import torch.nn as nn
from .envs import VecNormalize
# Get a render function
def get_render_func(venv):
if hasattr(venv, 'envs'):
return venv.envs[0].render
elif hasattr(venv, 'venv'):
return get_render_func(venv.venv)
elif hasattr(venv, 'env'):
... | 1,945 | 24.272727 | 88 | py |
SGP | SGP-main/RL_Experiments/rl_module/a2c_ppo_acktr/envs_bkp.py | # import os
# import gym
# import numpy as np
# import torch
# from gym.spaces.box import Box
# from baselines import bench
# from baselines.common.atari_wrappers import make_atari, wrap_deepmind
# from baselines.common.vec_env import VecEnvWrapper
# from baselines.common.vec_env.dummy_vec_env import DummyVecEnv
# fr... | 8,304 | 30.698473 | 96 | py |
PhyDNet | PhyDNet-master/main.py | import torch
import torchvision
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Variable
from torch.optim.lr_scheduler import ReduceLROnPlateau
import numpy as np
import random
import time
from models.models import ConvLSTM,PhyCell, EncoderRNN
from data.moving_mnist import MovingMNIST
f... | 7,446 | 43.861446 | 159 | py |
PhyDNet | PhyDNet-master/constrain_moments.py | from numpy import *
from numpy.linalg import *
from scipy.special import factorial
from functools import reduce
import torch
import torch.nn as nn
from functools import reduce
__all__ = ['M2K','K2M']
def _apply_axis_left_dot(x, mats):
assert x.dim() == len(mats)+1
sizex = x.size()
k = x.dim()-1
for i... | 4,381 | 26.049383 | 77 | py |
PhyDNet | PhyDNet-master/models/models.py | import torch
import torch.nn as nn
class PhyCell_Cell(nn.Module):
def __init__(self, input_dim, F_hidden_dim, kernel_size, bias=1):
super(PhyCell_Cell, self).__init__()
self.input_dim = input_dim
self.F_hidden_dim = F_hidden_dim
self.kernel_size = kernel_size
self.padding ... | 11,668 | 40.52669 | 161 | py |
PhyDNet | PhyDNet-master/data/moving_mnist.py | import gzip
import math
import numpy as np
import os
from PIL import Image
import random
import torch
import torch.utils.data as data
def load_mnist(root):
# Load MNIST dataset for generating training data.
path = os.path.join(root, 'train-images-idx3-ubyte.gz')
with gzip.open(path, 'rb') as f:
mni... | 5,231 | 31.90566 | 109 | py |
ExpensiveOptimBenchmark | ExpensiveOptimBenchmark-master/expensiveoptimbenchmark/problems/hpo.py | from .base import BaseProblem, maybe_int, maybe_float
from typing import Union
import pandas as pd
import numpy as np
try:
import pynisher
except:
pass
import xgboost
import os
from sklearn.pipeline import make_pipeline, Pipeline
from sklearn.model_selection import LeaveOneOut, StratifiedKFold, BaseCrossVali... | 24,714 | 38.292528 | 116 | py |
Perception-Evaluation | Perception-Evaluation-master/net.py | from torchvision import models
from collections import namedtuple
import torch
class Vgg16(torch.nn.Module):
def __init__(self, requires_grad=False):
super(Vgg16, self).__init__()
vgg_pretrained_features = models.vgg16(pretrained=True).features
self.slice1 = torch.nn.Sequential()
sel... | 1,372 | 33.325 | 92 | py |
Perception-Evaluation | Perception-Evaluation-master/MeasureFunction.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Aug 13 10:40:39 2018
@author: yellow
"""
import net
import numpy as np
import torch
from torch.autograd import Variable
from astropy.io import fits
class Load_img(object):
def __init__(self):
pass
def norm(self,img):
img = (img... | 2,339 | 24.714286 | 76 | py |
whisper-timestamped | whisper-timestamped-master/setup.py | import os
from setuptools import setup, find_packages
install_requires = open(os.path.join(os.path.dirname(__file__), "requirements.txt")).readlines()
version = None
license = None
with open(os.path.join(os.path.dirname(__file__), "whisper_timestamped", "transcribe.py")) as f:
for line in f:
if line.stri... | 1,465 | 32.318182 | 96 | py |
whisper-timestamped | whisper-timestamped-master/whisper_timestamped/transcribe.py | #!/usr/bin/env python3
__author__ = "Jérôme Louradour"
__credits__ = ["Jérôme Louradour"]
__license__ = "GPLv3"
__version__ = "1.12.20"
# Set some environment variables
import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '1' # Remove warning "This TensorFlow binary is optimized with oneAPI Deep Neural Network Library (one... | 112,021 | 46.167158 | 315 | py |
whisper-timestamped | whisper-timestamped-master/tests/test_transcribe.py | __author__ = "Jérôme Louradour"
__credits__ = ["Jérôme Louradour"]
__license__ = "GPLv3"
import unittest
import sys
import os
import subprocess
import shutil
import tempfile
import json
import torch
import jsonschema
FAIL_IF_REFERENCE_NOT_FOUND = True
GENERATE_NEW_ONLY = False
GENERATE_ALL = False
GENERATE_DEVICE_DEP... | 30,743 | 35 | 285 | py |
RPNet-Weakly-Supervised-Segmentation | RPNet-Weakly-Supervised-Segmentation-master/voc12/dataloader.py | import numpy as np
import torch
from torch.utils.data import Dataset
import os.path
import imageio
from misc import imutils
import random
IMG_FOLDER_NAME = "images"
ANNOT_FOLDER_NAME = "segmentations"
IGNORE = 255
CAT_LIST = ['aeroplane', 'bicycle', 'bird', 'boat',
'bottle', 'bus', 'car', 'cat', 'chair',
... | 10,850 | 32.909375 | 143 | py |
RPNet-Weakly-Supervised-Segmentation | RPNet-Weakly-Supervised-Segmentation-master/step/train_irn.py |
import torch
from torch.backends import cudnn
cudnn.enabled = True
from torch.utils.data import DataLoader
import voc12.dataloader
from misc import pyutils, torchutils, indexing
import importlib
def run(args):
path_index = indexing.PathIndex(radius=10, default_size=(args.irn_crop_size // 4, args.irn_crop_size //... | 5,417 | 46.946903 | 120 | py |
RPNet-Weakly-Supervised-Segmentation | RPNet-Weakly-Supervised-Segmentation-master/step/train_cam.py |
import torch
from torch.backends import cudnn
cudnn.enabled = True
from torch.utils.data import DataLoader
import torch.nn.functional as F
import importlib
import voc12.dataloader
from misc import pyutils, torchutils
def validate(model, data_loader):
print('validating ... ', flush=True, end='')
val_loss_m... | 5,224 | 36.321429 | 111 | py |
RPNet-Weakly-Supervised-Segmentation | RPNet-Weakly-Supervised-Segmentation-master/step/make_sem_seg_labels.py | import torch
from torch import multiprocessing, cuda
from torch.utils.data import DataLoader
import torch.nn.functional as F
from torch.backends import cudnn
import numpy as np
import importlib
import os
import imageio
import voc12.dataloader
from misc import torchutils, indexing
cudnn.enabled = True
def _work(proc... | 2,600 | 34.148649 | 137 | py |
RPNet-Weakly-Supervised-Segmentation | RPNet-Weakly-Supervised-Segmentation-master/step/make_cam_bk.py | import torch
from torch.utils.data import DataLoader
import torch.nn.functional as F
from torch.backends import cudnn
import voc12.dataloader
cudnn.enabled = True
def _work(process_id, model, dataset, args):
databin = dataset[process_id]
n_gpus = torch.cuda.device_count()
# n_gpus = 1
data_loader =... | 7,144 | 34.904523 | 114 | py |
RPNet-Weakly-Supervised-Segmentation | RPNet-Weakly-Supervised-Segmentation-master/step/make_cocoann.py | import numpy as np
import voc12.dataloader
from torch.utils.data import DataLoader
from pycococreatortools import pycococreatortools
import os
import json
VOC2012_JSON_FOLDER = ""
def run(args):
infer_dataset = voc12.dataloader.VOC12ImageDataset(args.infer_list, voc12_root=args.voc12_root)
infer_data_loader... | 1,774 | 33.134615 | 111 | py |
RPNet-Weakly-Supervised-Segmentation | RPNet-Weakly-Supervised-Segmentation-master/step/cam_to_ir_label.py |
import os
import numpy as np
import imageio
from torch import multiprocessing
from torch.utils.data import DataLoader
import voc12.dataloader
from misc import torchutils, imutils
def _work(process_id, infer_dataset, args):
databin = infer_dataset[process_id]
infer_data_loader = DataLoader(databin, shuffle... | 2,303 | 39.421053 | 126 | py |
RPNet-Weakly-Supervised-Segmentation | RPNet-Weakly-Supervised-Segmentation-master/step/make_cam.py | import torch
from torch import multiprocessing, cuda
from torch.utils.data import DataLoader
import torch.nn.functional as F
from torch.backends import cudnn
import numpy as np
import importlib
import os
import voc12.dataloader
from misc import torchutils, imutils
cudnn.enabled = True
def _work(process_id, model, d... | 2,921 | 35.525 | 114 | py |
RPNet-Weakly-Supervised-Segmentation | RPNet-Weakly-Supervised-Segmentation-master/misc/indexing.py | import torch
import torch.nn.functional as F
import numpy as np
class PathIndex:
def __init__(self, radius, default_size):
self.radius = radius
self.radius_floor = int(np.ceil(radius) - 1)
self.search_paths, self.search_dst = self.get_search_paths_dst(self.radius)
self.path_indi... | 6,025 | 33.83237 | 129 | py |
RPNet-Weakly-Supervised-Segmentation | RPNet-Weakly-Supervised-Segmentation-master/misc/torchutils.py |
import torch
from torch.utils.data import Subset
import numpy as np
import math
class PolyOptimizer(torch.optim.SGD):
def __init__(self, params, lr, weight_decay, max_step, momentum=0.9):
super().__init__(params, lr, weight_decay)
self.global_step = 0
self.max_step = max_step
s... | 2,048 | 25.61039 | 104 | py |
RPNet-Weakly-Supervised-Segmentation | RPNet-Weakly-Supervised-Segmentation-master/net/resnet101.py | import torch.nn as nn
import torch.nn.functional as F
import torch.utils.model_zoo as model_zoo
model_urls = {
'resnet50': 'https://download.pytorch.org/models/resnet50-19c8e357.pth'
}
class FixedBatchNorm(nn.BatchNorm2d):
def forward(self, input):
return F.batch_norm(input, self.running_mean, self.r... | 4,503 | 32.362963 | 103 | py |
RPNet-Weakly-Supervised-Segmentation | RPNet-Weakly-Supervised-Segmentation-master/net/resnet50_cam.py | import torch.nn as nn
import torch.nn.functional as F
from misc import torchutils
from net import resnext as resnet50
import torch
from net import Gaussian
class _NonLocalBlockND(nn.Module):
def __init__(self, in_channels, inter_channels=None, dimension=3, sub_sample=True, bn_layer=True):
super(_NonLocalBl... | 13,117 | 38.87234 | 129 | py |
RPNet-Weakly-Supervised-Segmentation | RPNet-Weakly-Supervised-Segmentation-master/net/Gaussian.py | import math
import numbers
import torch
from torch import nn
from torch.nn import functional as F
class GaussianSmoothing(nn.Module):
"""
Apply gaussian smoothing on a
1d, 2d or 3d tensor. Filtering is performed seperately for each channel
in the input using a depthwise convolution.
Arguments:
... | 2,589 | 35.478873 | 103 | py |
RPNet-Weakly-Supervised-Segmentation | RPNet-Weakly-Supervised-Segmentation-master/net/resnext.py | import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.utils.model_zoo as model_zoo
# model_urls = {
# 'resnext50_32x4d': 'https://download.pytorch.org/models/resnext50_32x4d-7cdf4587.pth',
# }
model_urls = {
'resnet18': 'https://download.pytorch.org/models/resnet18-5c106cde.pth',
... | 12,054 | 38.395425 | 107 | py |
RPNet-Weakly-Supervised-Segmentation | RPNet-Weakly-Supervised-Segmentation-master/net/resnet50_irn.py | import torch
import torch.nn as nn
import torch.nn.functional as F
from net import resnet50
class _NonLocalBlockND(nn.Module):
def __init__(self, in_channels, inter_channels=None, dimension=3, sub_sample=True, bn_layer=True):
super(_NonLocalBlockND, self).__init__()
assert dimension in [1, 2, 3]
... | 12,603 | 36.179941 | 132 | py |
RPNet-Weakly-Supervised-Segmentation | RPNet-Weakly-Supervised-Segmentation-master/net/resnet50.py | import torch.nn as nn
import torch.nn.functional as F
import torch.utils.model_zoo as model_zoo
model_urls = {
'resnet50': 'https://download.pytorch.org/models/resnet50-19c8e357.pth'
}
class FixedBatchNorm(nn.BatchNorm2d):
def forward(self, input):
return F.batch_norm(input, self.running_mean, self.r... | 4,502 | 32.110294 | 103 | py |
FINet | FINet-main/evaluate.py | import argparse
import logging
import os
import dataset.data_loader as data_loader
import model.net as net
from common import utils
from loss.losses import compute_losses, compute_metrics
from common.manager import Manager
import megengine.distributed as dist
import megengine.functional as F
parser = argparse.Argum... | 8,002 | 39.015 | 134 | py |
FINet | FINet-main/common/quaternion.py | import torch
import numpy as np
import megengine.functional as F
def mge_qmul(q1, q2):
"""
Multiply quaternion(s) q2q1, rotate q1 first, rotate q2 second.
Expects two equally-sized tensors of shape (*, 4), where * denotes any number of dimensions.
Returns q*r as a tensor of shape (*, 4).
"""
a... | 10,304 | 31.507886 | 127 | py |
GKD | GKD-main/main.py | # -*- coding: utf-8 -*-
"""
@Author: Su Lu
@Date: 2021-06-07 19:15:01
"""
import argparse
import random
import importlib
import platform
import copy
import numpy as np
import torch
from torch import nn
from torchvision import models
from networks import resnet, wide_resnet, mobile_net
from Train import train_stag... | 12,897 | 46.419118 | 138 | py |
GKD | GKD-main/pretrain.py | # -*- coding: utf-8 -*-
"""
@Author: Su Lu
@Date: 2020-12-08 19:46:19
"""
import argparse
import random
import importlib
import platform
import numpy as np
import torch
from torch import nn
from torchvision import models
from Train import pretrain
from utils import global_variable as GV
import os
def display_args... | 6,287 | 40.368421 | 138 | py |
GKD | GKD-main/Metric.py | # -*- coding: utf-8 -*-
"""
@Author: Su Lu
@Date: 2021-06-07 19:15:01
"""
import argparse
import random
import importlib
import platform
import copy
import numpy as np
import torch
from torch import nn
from torch.distributions.categorical import Categorical
from torchvision import models
from matplotlib import pyp... | 11,638 | 40.716846 | 138 | py |
GKD | GKD-main/Test.py | # -*- coding: utf-8 -*-
"""
@Author: Su Lu
@Date: 2020-12-09 20:03:32
"""
import torch
from torch.nn import functional as F
from utils import global_variable as GV
def test(args, data_loader, network):
accuracy = 0
network.eval()
for _, batch in enumerate(data_loader):
images, labels, _, _ = batc... | 2,410 | 34.455882 | 97 | py |
GKD | GKD-main/Train.py | # -*- coding: utf-8 -*-
"""
@Author: Su Lu
@Date: 2020-12-08 20:59:35
"""
import os
import warnings
warnings.filterwarnings('ignore')
import numpy as np
import torch
from torch import nn
from torch.optim import SGD
from torch.optim.lr_scheduler import MultiStepLR, CosineAnnealingLR
from torch.nn import functional a... | 14,294 | 43.811912 | 122 | py |
GKD | GKD-main/networks/resnet.py | # -*- coding: utf-8 -*-
"""
@Author: Su Lu
@Date: 2019-07-15 15:21:44
"""
import numpy as np
import torch
from torch import nn
from torch.nn import init
from torch.nn import functional as F
def conv_init(m):
classname = m.__class__.__name__
if classname.find('Conv') != -1:
init.xavier_uniform_(m.wei... | 6,041 | 39.28 | 145 | py |
GKD | GKD-main/networks/wide_resnet.py | # -*- coding: utf-8 -*-
"""
@Author: Su Lu
@Date: 2019-07-15 13:57:46
"""
import numpy as np
import torch
from torch import nn
from torch.nn import init
from torch.nn import functional as F
def conv_init(m):
classname = m.__class__.__name__
if classname.find('Conv') != -1:
init.xavier_uniform_(m.wei... | 6,376 | 42.380952 | 145 | py |
GKD | GKD-main/networks/mobile_net.py | # -*- coding: utf-8 -*-
"""
@Author: Su Lu
@Date: 2019-09-16 16:24:31
"""
import numpy as np
import torch
from torch import nn
from torch.nn import init
from torch.nn import functional as F
def conv_init(m):
classname = m.__class__.__name__
if classname.find('Conv') != -1:
init.xavier_uniform_(m.wei... | 4,277 | 34.94958 | 129 | py |
GKD | GKD-main/dataloaders/CUB-200.py | # -*- coding: utf-8 -*-
"""
@Author: Su Lu
@Date: 2020-12-08 19:22:12
"""
import pickle
from PIL import Image
import numpy as np
from torch.utils.data import Dataset
from torch.utils.data import DataLoader
from torchvision import transforms
class MyDataset(Dataset):
def __init__(self, data_path, flag_mode, n_... | 3,920 | 31.139344 | 134 | py |
GKD | GKD-main/dataloaders/CIFAR-100.py | # -*- coding: utf-8 -*-
"""
@Author: Su Lu
@Date: 2020-12-08 15:42:03
"""
import pickle
from PIL import Image
import numpy as np
from torch.utils.data import Dataset
from torch.utils.data import DataLoader
from torchvision import transforms
class MyDataset(Dataset):
def __init__(self, data_path, flag_mode, n_... | 3,996 | 32.308333 | 134 | py |
GKD | GKD-main/utils/check.py | # -*- coding: utf-8 -*-
"""
@Author: Su Lu
@Date: 2021-06-10 13:03:33
"""
import argparse
import random
import importlib
import platform
import copy
import sys
sys.path.append('..')
import numpy as np
import torch
from torch import nn
from torchvision import models
from utils import global_variable as GV
import os... | 6,229 | 42.263889 | 134 | py |
GKD | GKD-main/utils/triplet.py | # -*- coding: utf-7 -*-
"""
@Author: Su Lu
@Date: 2020-12-29 12:18:25
"""
import torch
def merge(args, anchor_id, positive_id, negative_id):
k = torch.add(anchor_id * args.batch_size, positive_id)
sorted_k, sorted_index = torch.sort(k)
sorted_n = negative_id[sorted_index]
unique_k, counts = torch.un... | 847 | 29.285714 | 92 | py |
GKD | GKD-main/utils/metric.py | # -*- coding: utf-8 -*-
"""
@Author Su Lu
@Date: 2021-07-20 14:19:29
"""
import argparse
import random
import importlib
import platform
import copy
import sys
sys.path.append('..')
import numpy as np
from PIL import Image
import torch
from torch import nn
from torchvision import models
from sklearn.metrics import ... | 11,064 | 41.072243 | 138 | py |
neurophox | neurophox-master/setup.py | #!/usr/bin/env python
from setuptools import setup, find_packages
project_name = "neurophox"
requirements = [
"numpy>=1.16",
"scipy",
"tensorflow>=2.0",
"torch>=1.3"
]
setup(
name=project_name,
version="0.1.0-beta.0",
packages=find_packages(),
description='A simulation framework for u... | 925 | 26.235294 | 90 | py |
neurophox | neurophox-master/tests/test_layers.py | import tensorflow as tf
import numpy as np
import pytest
from neurophox.config import TF_COMPLEX, NP_COMPLEX
import itertools
from neurophox.numpy import RMNumpy, TMNumpy, PRMNumpy, BMNumpy, MeshNumpyLayer
from neurophox.tensorflow import RM, TM, PRM, BM, MeshLayer
from neurophox.torch import RMTorch, TMTorch, PRMTor... | 7,685 | 43.172414 | 103 | py |
neurophox | neurophox-master/tests/test_phasecontrolfn.py | import tensorflow as tf
import torch
import numpy as np
import itertools
from scipy.stats import unitary_group
from neurophox.config import TF_COMPLEX
from neurophox.helpers import fix_phase_tf, tri_phase_tf, fix_phase_torch
from neurophox.tensorflow import MeshLayer
from neurophox.torch import RMTorch
from neurophox.n... | 4,624 | 45.717172 | 105 | py |
neurophox | neurophox-master/doc/source/conf.py | # Configuration file for the Sphinx documentation builder.
#
# This file only contains a selection of the most common options. For a full
# list see the documentation:
# http://www.sphinx-doc.org/en/master/config
# -- Path setup --------------------------------------------------------------
# If extensions (or module... | 2,408 | 30.285714 | 104 | py |
neurophox | neurophox-master/neurophox/initializers.py | from typing import Tuple, Union, Optional
import tensorflow as tf
try:
import torch
from torch.nn import Parameter
except ImportError:
# if the user did not install pytorch, just do tensorflow stuff
pass
import numpy as np
from .config import TF_FLOAT, NP_FLOAT, TEST_SEED, T_FLOAT
from .helpers impo... | 9,815 | 40.243697 | 130 | py |
neurophox | neurophox-master/neurophox/config.py | import tensorflow as tf
import numpy as np
import torch
# Backends
PYTORCH = 'torch'
TFKERAS = 'tf'
NUMPY = 'numpy'
# Types (for memory)
NP_COMPLEX = np.complex128
NP_FLOAT = np.float64
TF_COMPLEX = tf.complex64
TF_FLOAT = tf.float32
T_FLOAT = torch.double
T_COMPLEX = torch.cdouble
# Test seed
TEST_SEED = 31415... | 393 | 11.709677 | 26 | py |
neurophox | neurophox-master/neurophox/meshmodel.py | from typing import Optional, Union, Tuple, List
import numpy as np
try:
import torch
from torch.nn import Parameter
except ImportError:
pass
from .helpers import butterfly_permutation, grid_permutation, to_stripe_array, prm_permutation, \
get_efficient_coarse_grain_block_sizes, get_default_coarse_grain... | 15,327 | 54.33574 | 169 | py |
neurophox | neurophox-master/neurophox/helpers.py | from typing import Optional, Callable, Tuple
import numpy as np
import tensorflow as tf
try:
import torch
except ImportError:
# if the user did not install pytorch, just do tensorflow stuff
pass
from scipy.stats import multivariate_normal
from .config import NP_FLOAT
def to_stripe_array(nparray: np.nda... | 12,732 | 41.023102 | 120 | py |
neurophox | neurophox-master/neurophox/torch/generic.py | from typing import List, Optional, Callable
import torch
from torch.nn import Module, Parameter
import numpy as np
from ..numpy.generic import MeshPhases
from ..config import BLOCH, SINGLEMODE
from ..meshmodel import MeshModel
from ..helpers import pairwise_off_diag_permutation, plot_complex_matrix
class Transforme... | 21,861 | 45.713675 | 213 | py |
neurophox | neurophox-master/neurophox/ml/linear.py | from typing import Optional, Callable, List, Union
import numpy as np
import tensorflow as tf
import pickle
from ..config import TF_COMPLEX, NP_COMPLEX
from ..helpers import random_gaussian_batch
from ..tensorflow import MeshLayer, SVD
def complex_mse(y_true: tf.Tensor, y_pred: tf.Tensor):
"""
Args:
... | 7,460 | 42.631579 | 142 | py |
neurophox | neurophox-master/neurophox/tensorflow/generic.py | from typing import List, Tuple, Optional, Callable
import tensorflow as tf
from tensorflow.keras.layers import Layer, Activation
import numpy as np
from ..numpy.generic import MeshPhases
from ..meshmodel import MeshModel
from ..helpers import pairwise_off_diag_permutation, plot_complex_matrix, inverse_permutation
fro... | 26,321 | 43.462838 | 212 | py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.