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
xcos
xcos-master/src/worker/tester.py
import os import time import torch from torchvision.utils import save_image from .worker_template import WorkerTemplate from data_loader.base_data_loader import BaseDataLoader from pipeline.base_pipeline import BasePipeline from utils.global_config import global_config from utils.logging_config import logger from utils...
4,707
42.192661
118
py
xcos
xcos-master/src/worker/worker_template.py
import time from abc import ABC, abstractmethod import torch from torchvision.utils import make_grid from data_loader.base_data_loader import BaseDataLoader from pipeline.base_pipeline import BasePipeline from utils.global_config import global_config from utils.util import batch_visualize_xcos class WorkerTemplate(...
6,516
38.981595
101
py
xcos
xcos-master/src/worker/validator.py
import torch from .training_worker import TrainingWorker from pipeline.base_pipeline import BasePipeline class Validator(TrainingWorker): """ Validator class Note: Inherited from WorkerTemplate. """ def __init__(self, pipeline: BasePipeline, *args): super().__init__(pipeline, *arg...
1,686
39.166667
113
py
xcos
xcos-master/src/data_loader/data_loaders.py
import os import sys sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(__file__)))) # noqa from torchvision import transforms from .base_data_loader import BaseDataLoader from .mnist import MnistDataset from .mnist_result import MnistResultDataset from .face_datasets import SiameseImageFolder, InsightF...
5,081
40.655738
98
py
xcos
xcos-master/src/data_loader/base_data_loader.py
import numpy as np from torch.utils.data import DataLoader from torch.utils.data.dataloader import default_collate from torch.utils.data.sampler import SubsetRandomSampler # Add this to initialize workers of dataloader to avoid fixed numpy random # seeds for each training epoch. For a clearer explanation please refer...
2,242
32.477612
112
py
xcos
xcos-master/src/data_loader/face_datasets.py
import cv2 import os import os.path as op import warnings from glob import glob import numpy as np import pandas as pd from PIL import Image import bcolz import torch import torch.nn as nn from torchvision import transforms, datasets from torch.utils.data import Dataset from torch.utils.data.sampler import BatchSampler...
49,157
36.212718
107
py
xcos
xcos-master/src/data_loader/mnist_result.py
import numpy as np from torch.utils.data import Dataset class MnistResultDataset(Dataset): """ Customized MNIST result dataset demo """ def __init__(self, result_filename, key='model_output'): self.key = key self.results = self._load_data(result_filename, key) def _load_data(self,...
661
24.461538
60
py
xcos
xcos-master/src/data_loader/mnist.py
from torchvision import datasets class MnistDataset(datasets.MNIST): """ Customized MNIST dataset demo """ def __init__(self, data_dir, train, download, transform): super().__init__(data_dir, train=train, download=download, transform=transform) def __getitem__(self, index): """ Ov...
532
27.052632
87
py
xcos
xcos-master/src/utils/visualization.py
try: from torch.utils.tensorboard import SummaryWriter except ImportError: print("Using tensorboardX instead of built-in tensorboard (need PyTorch 1.2+ with Tensorboard 1.14+)") from tensorboardX import SummaryWriter class WriterTensorboard(): def __init__(self, writer_dir, logger, enable): se...
1,723
37.311111
114
py
xcos
xcos-master/src/utils/insight2xcos.py
# from model.face_recog import Backbone_FC2Conv, Backbone # from model.xcos_modules import XCosAttention # backbone = Backbone_FC2Conv(50, 0.6, 'ir_se') # attention = XCosAttention(use_softmax=True, softmax_t=1, chw2hwc=True) # backbone_target = Backbone(50, # 0.6, # ...
2,258
43.294118
120
py
xcos
xcos-master/src/utils/insight_to_normal_face_model.py
# from model.face_recog import Backbone_FC2Conv, Backbone # from model.xcos_modules import XCosAttention # backbone = Backbone_FC2Conv(50, 0.6, 'ir_se') # attention = XCosAttention(use_softmax=True, softmax_t=1, chw2hwc=True) # backbone_target = Backbone(50, # 0.6, # ...
1,476
33.348837
86
py
xcos
xcos-master/src/utils/util.py
import os import os.path as op from glob import glob import importlib.util import torch import numpy as np import io import cv2 import base64 import seaborn as sns from PIL import Image from torchvision.transforms import ToTensor from matplotlib import pyplot as plt lib_path = op.abspath(op.join(__file__, op.pardir...
11,115
31.127168
90
py
xcos
xcos-master/src/utils/verification.py
import numpy as np from sklearn.model_selection import KFold import matplotlib.pyplot as plt import io from PIL import Image from torchvision import transforms def calculate_accuracy(threshold, dist, actual_issame, useCos=False): ''' if useCos = True, then view 'dist' variable as cos ''' if useCos: ...
4,936
33.284722
95
py
xcos
xcos-master/src/model/base_model.py
import torch.nn as nn import numpy as np from utils.logging_config import logger class BaseModel(nn.Module): """ Base class for all models """ def __init__(self): super(BaseModel, self).__init__() def forward(self, *input): """ Forward pass logic :return: Model ...
672
20.709677
79
py
xcos
xcos-master/src/model/loss.py
import torch import torch.nn as nn class BaseLoss(nn.Module): def __init__(self, output_key, target_key, nickname=None, weight=1): super().__init__() self.output_key = output_key self.target_key = target_key self.weight = weight self.nickname = self.__class__.__name__ if ni...
4,210
32.688
90
py
xcos
xcos-master/src/model/face_recog.py
from torch.nn import (Linear, Conv2d, BatchNorm1d, BatchNorm2d, PReLU, ReLU, Sigmoid, Dropout, MaxPool2d, AdaptiveAvgPool2d, Sequential, Module, Parameter) # import torch.nn.functional as F import torch from collections import namedtuple import math from .networks import nor...
15,351
37.094293
112
py
xcos
xcos-master/src/model/model.py
import os import sys sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(__file__)))) # noqa import torch import torch.nn as nn import torch.nn.functional as F from .base_model import BaseModel from .networks import MnistGenerator, MnistDiscriminator from .face_recog import Backbone_FC2Conv, Backbone, A...
9,784
39.26749
102
py
xcos
xcos-master/src/model/networks.py
import torch import torch.nn as nn import torch.nn.functional as F from torch.nn.utils import spectral_norm def normal_init(m, mean, std): if isinstance(m, nn.ConvTranspose2d) or isinstance(m, nn.Conv2d): m.weight.data.normal_(mean, std) m.bias.data.zero_() class MnistGenerator(nn.Module): #...
2,779
38.714286
129
py
xcos
xcos-master/src/model/xcos_modules.py
import torch import torch.nn as nn import torch.nn.functional as F from .networks import normal_init cos = nn.CosineSimilarity(dim=1, eps=1e-6) def l2normalize(x): return F.normalize(x, p=2, dim=1) class FrobeniusInnerProduct(nn.Module): def __init__(self): super(FrobeniusInnerProduct, self).__in...
10,474
33.916667
94
py
xcos
xcos-master/src/model/metric.py
import os import torch from abc import abstractmethod import tempfile import numpy as np from torchvision import transforms from utils.util import DeNormalize, lib_path, import_given_path from utils.verification import evaluate_accuracy from utils.logging_config import logger class BaseMetric(torch.nn.Module): ...
8,283
35.982143
114
py
PrincipledPruningBNN
PrincipledPruningBNN-main/bayesian-tensorflow/src/bayesian_tensorflow/losses.py
# Imports import math from keras import backend as K import tensorflow as tf # Accuracy loss function for regression models, for Bayes-by-Backprop @tf.function def AccLossBBB(y_true, y_pred): """ This function computes the accuracy loss term of the Variational Free Energy (VFE) for the Bayes-by-Backprop ...
1,705
30.592593
100
py
PrincipledPruningBNN
PrincipledPruningBNN-main/bayesian-tensorflow/src/bayesian_tensorflow/activations.py
# Imports import math from keras import backend as K import tensorflow as tf # ReLU function @tf.function def relu_moments(h_mean, h_var): """ This functions computes the first and second (central) moment of a Normal distribution passing through a ReLU function. It takes the mean and variance of...
2,544
28.252874
94
py
PrincipledPruningBNN
PrincipledPruningBNN-main/bayesian-tensorflow/src/bayesian_tensorflow/layers/bayes_by_backprop.py
# Imports from keras import backend as K from keras import initializers, activations import tensorflow as tf # Dense layer class DenseBBB(tf.keras.layers.Layer): """ Variational fully connected layer (dense), following Bayes-by-Backprop (BBB). It takes the number of units as its input, all other inp...
22,719
41.706767
132
py
PrincipledPruningBNN
PrincipledPruningBNN-main/bayesian-tensorflow/src/bayesian_tensorflow/layers/variance_backpropagation.py
# Imports import math from keras import backend as K from keras import initializers import tensorflow as tf # Local functions from bayesian_tensorflow import activations # Dense layer class DenseVBP(tf.keras.layers.Layer): """ Variational fully connected layer (dense), following Variance Back-Propagation (V...
21,930
41.09405
132
py
Stochastic-Quantization
Stochastic-Quantization-master/caffe/tools/extra/summarize.py
#!/usr/bin/env python """Net summarization tool. This tool summarizes the structure of a net in a concise but comprehensive tabular listing, taking a prototxt file as input. Use this tool to check at a glance that the computation you've specified is the computation you expect. """ from caffe.proto import caffe_pb2 ...
4,880
33.617021
95
py
Stochastic-Quantization
Stochastic-Quantization-master/caffe/tools/extra/parse_log.py
#!/usr/bin/env python """ Parse training log Evolved from parse_log.sh """ import os import re import extract_seconds import argparse import csv from collections import OrderedDict def parse_log(path_to_log): """Parse log file Returns (train_dict_list, test_dict_list) train_dict_list and test_dict_lis...
7,136
32.824645
86
py
Stochastic-Quantization
Stochastic-Quantization-master/caffe/examples/web_demo/app.py
import os import time import cPickle import datetime import logging import flask import werkzeug import optparse import tornado.wsgi import tornado.httpserver import numpy as np import pandas as pd from PIL import Image import cStringIO as StringIO import urllib import exifutil import caffe REPO_DIRNAME = os.path.abs...
7,793
33.184211
105
py
Stochastic-Quantization
Stochastic-Quantization-master/caffe/examples/pycaffe/caffenet.py
from __future__ import print_function from caffe import layers as L, params as P, to_proto from caffe.proto import caffe_pb2 # helper function for common structures def conv_relu(bottom, ks, nout, stride=1, pad=0, group=1): conv = L.Convolution(bottom, kernel_size=ks, stride=stride, ...
2,112
36.732143
91
py
Stochastic-Quantization
Stochastic-Quantization-master/caffe/examples/pycaffe/tools.py
import numpy as np class SimpleTransformer: """ SimpleTransformer is a simple class for preprocessing and deprocessing images for caffe. """ def __init__(self, mean=[128, 128, 128]): self.mean = np.array(mean, dtype=np.float32) self.scale = 1.0 def set_mean(self, mean): ...
3,457
27.344262
79
py
Stochastic-Quantization
Stochastic-Quantization-master/caffe/examples/pycaffe/layers/pascal_multilabel_datalayers.py
# imports import json import time import pickle import scipy.misc import skimage.io import caffe import numpy as np import os.path as osp from xml.dom import minidom from random import shuffle from threading import Thread from PIL import Image from tools import SimpleTransformer class PascalMultilabelDataLayerSync...
6,846
30.552995
78
py
Stochastic-Quantization
Stochastic-Quantization-master/caffe/examples/pycaffe/layers/pyloss.py
import caffe import numpy as np class EuclideanLossLayer(caffe.Layer): """ Compute the Euclidean Loss in the same manner as the C++ EuclideanLossLayer to demonstrate the class interface for developing layers in Python. """ def setup(self, bottom, top): # check input pair if len(bo...
1,223
31.210526
79
py
Stochastic-Quantization
Stochastic-Quantization-master/caffe/examples/finetune_flickr_style/assemble_data.py
#!/usr/bin/env python """ Form a subset of the Flickr Style data, download images to dirname, and write Caffe ImagesDataLayer training file. """ import os import urllib import hashlib import argparse import numpy as np import pandas as pd from skimage import io import multiprocessing # Flickr returns a special image i...
3,636
35.737374
94
py
Stochastic-Quantization
Stochastic-Quantization-master/caffe/src/caffe/test/test_data/generate_sample_data.py
""" Generate data used in the HDF5DataLayer and GradientBasedSolver tests. """ import os import numpy as np import h5py script_dir = os.path.dirname(os.path.abspath(__file__)) # Generate HDF5DataLayer sample_data.h5 num_cols = 8 num_rows = 10 height = 6 width = 5 total_size = num_cols * num_rows * height * width da...
2,104
24.670732
70
py
Stochastic-Quantization
Stochastic-Quantization-master/caffe/python/draw_net.py
#!/usr/bin/env python """ Draw a graph of the net architecture. """ from argparse import ArgumentParser, ArgumentDefaultsHelpFormatter from google.protobuf import text_format import caffe import caffe.draw from caffe.proto import caffe_pb2 def parse_args(): """Parse input arguments """ parser = Argument...
1,934
31.79661
81
py
Stochastic-Quantization
Stochastic-Quantization-master/caffe/python/detect.py
#!/usr/bin/env python """ detector.py is an out-of-the-box windowed detector callable from the command line. By default it configures and runs the Caffe reference ImageNet model. Note that this model was trained for image classification and not detection, and finetuning for detection can be expected to improve results...
5,734
31.95977
88
py
Stochastic-Quantization
Stochastic-Quantization-master/caffe/python/classify.py
#!/usr/bin/env python """ classify.py is an out-of-the-box image classifer callable from the command line. By default it configures and runs the Caffe reference ImageNet model. """ import numpy as np import os import sys import argparse import glob import time import caffe def main(argv): pycaffe_dir = os.path....
4,262
29.669065
88
py
Stochastic-Quantization
Stochastic-Quantization-master/caffe/python/train.py
#!/usr/bin/env python """ Trains a model using one or more GPUs. """ from multiprocessing import Process import caffe def train( solver, # solver proto definition snapshot, # solver snapshot to restore gpus, # list of device ids timing=False, # show timing info for compute and com...
3,145
30.148515
85
py
Stochastic-Quantization
Stochastic-Quantization-master/caffe/python/caffe/net_spec.py
"""Python net specification. This module provides a way to write nets directly in Python, using a natural, functional style. See examples/pycaffe/caffenet.py for an example. Currently this works as a thin wrapper around the Python protobuf interface, with layers and parameters automatically generated for the "layers"...
8,277
34.835498
88
py
Stochastic-Quantization
Stochastic-Quantization-master/caffe/python/caffe/classifier.py
#!/usr/bin/env python """ Classifier is an image classifier specialization of Net. """ import numpy as np import caffe class Classifier(caffe.Net): """ Classifier extends Net for image class prediction by scaling, center cropping, or oversampling. Parameters ---------- image_dims : dimensio...
3,537
34.737374
78
py
Stochastic-Quantization
Stochastic-Quantization-master/caffe/python/caffe/coord_map.py
""" Determine spatial relationships between layers to relate their coordinates. Coordinates are mapped from input-to-output (forward), but can be mapped output-to-input (backward) by the inverse mapping too. This helps crop and align feature maps among other uses. """ from __future__ import division import numpy as np...
6,721
35.139785
79
py
Stochastic-Quantization
Stochastic-Quantization-master/caffe/python/caffe/detector.py
#!/usr/bin/env python """ Do windowed detection by classifying a number of images/crops at once, optionally using the selective search window proposal method. This implementation follows ideas in Ross Girshick, Jeff Donahue, Trevor Darrell, Jitendra Malik. Rich feature hierarchies for accurate object detection...
8,541
38.364055
80
py
Stochastic-Quantization
Stochastic-Quantization-master/caffe/python/caffe/__init__.py
from .pycaffe import Net, SGDSolver, NesterovSolver, AdaGradSolver, RMSPropSolver, AdaDeltaSolver, AdamSolver, NCCL, Timer from ._caffe import init_log, log, set_mode_cpu, set_mode_gpu, set_device, Layer, get_solver, layer_type_list, set_random_seed, solver_count, set_solver_count, solver_rank, set_solver_rank, set_mul...
552
60.444444
216
py
Stochastic-Quantization
Stochastic-Quantization-master/caffe/python/caffe/pycaffe.py
""" Wrap the internal caffe C++ module (_caffe.so) with a clean, Pythonic interface. """ from collections import OrderedDict try: from itertools import izip_longest except: from itertools import zip_longest as izip_longest import numpy as np from ._caffe import Net, SGDSolver, NesterovSolver, AdaGradSolver, \...
11,615
32.572254
89
py
Stochastic-Quantization
Stochastic-Quantization-master/caffe/python/caffe/draw.py
""" Caffe network visualization: draw the NetParameter protobuffer. .. note:: This requires pydot>=1.0.2, which is not included in requirements.txt since it requires graphviz and other prerequisites outside the scope of the Caffe. """ from caffe.proto import caffe_pb2 """ pydot is not supported under p...
8,789
34.877551
112
py
Stochastic-Quantization
Stochastic-Quantization-master/caffe/python/caffe/io.py
import numpy as np import skimage.io from scipy.ndimage import zoom from skimage.transform import resize try: # Python3 will most likely not be able to load protobuf from caffe.proto import caffe_pb2 except: import sys if sys.version_info >= (3, 0): print("Failed to include caffe_pb2, things mi...
12,743
32.1875
110
py
Stochastic-Quantization
Stochastic-Quantization-master/caffe/python/caffe/test/test_coord_map.py
import unittest import numpy as np import random import caffe from caffe import layers as L from caffe import params as P from caffe.coord_map import coord_map_from_to, crop def coord_net_spec(ks=3, stride=1, pad=0, pool=2, dstride=2, dpad=0): """ Define net spec for simple conv-pool-deconv pattern common t...
6,894
34.725389
79
py
Stochastic-Quantization
Stochastic-Quantization-master/caffe/python/caffe/test/test_python_layer_with_param_str.py
import unittest import tempfile import os import six import caffe class SimpleParamLayer(caffe.Layer): """A layer that just multiplies by the numeric value of its param string""" def setup(self, bottom, top): try: self.value = float(self.param_str) except ValueError: ...
2,031
31.774194
79
py
Stochastic-Quantization
Stochastic-Quantization-master/caffe/python/caffe/test/test_io.py
import numpy as np import unittest import caffe class TestBlobProtoToArray(unittest.TestCase): def test_old_format(self): data = np.zeros((10,10)) blob = caffe.proto.caffe_pb2.BlobProto() blob.data.extend(list(data.flatten())) shape = (1,1,10,10) blob.num, blob.channels, b...
1,694
28.736842
65
py
Stochastic-Quantization
Stochastic-Quantization-master/caffe/python/caffe/test/test_solver.py
import unittest import tempfile import os import numpy as np import six import caffe from test_net import simple_net_file class TestSolver(unittest.TestCase): def setUp(self): self.num_output = 13 net_f = simple_net_file(self.num_output) f = tempfile.NamedTemporaryFile(mode='w+', delete=F...
2,165
33.380952
76
py
Stochastic-Quantization
Stochastic-Quantization-master/caffe/python/caffe/test/test_layer_type_list.py
import unittest import caffe class TestLayerTypeList(unittest.TestCase): def test_standard_types(self): #removing 'Data' from list for type_name in ['Data', 'Convolution', 'InnerProduct']: self.assertIn(type_name, caffe.layer_type_list(), '%s not in layer_type_lis...
338
27.25
65
py
Stochastic-Quantization
Stochastic-Quantization-master/caffe/python/caffe/test/test_net.py
import unittest import tempfile import os import numpy as np import six from collections import OrderedDict import caffe def simple_net_file(num_output): """Make a simple net prototxt, based on test_net.cpp, returning the name of the (temporary) file.""" f = tempfile.NamedTemporaryFile(mode='w+', delete...
11,640
28.848718
82
py
Stochastic-Quantization
Stochastic-Quantization-master/caffe/python/caffe/test/test_draw.py
import os import unittest from google.protobuf import text_format import caffe.draw from caffe.proto import caffe_pb2 def getFilenames(): """Yields files in the source tree which are Net prototxts.""" result = [] root_dir = os.path.abspath(os.path.join( os.path.dirname(__file__), '..', '..', '.....
1,114
28.342105
79
py
Stochastic-Quantization
Stochastic-Quantization-master/caffe/python/caffe/test/test_nccl.py
import sys import unittest import caffe class TestNCCL(unittest.TestCase): def test_newuid(self): """ Test that NCCL uids are of the proper type according to python version """ if caffe.has_nccl(): uid = caffe.NCCL.new_uid() if sys.version_info.maj...
457
21.9
55
py
Stochastic-Quantization
Stochastic-Quantization-master/caffe/python/caffe/test/test_net_spec.py
import unittest import tempfile import caffe from caffe import layers as L from caffe import params as P def lenet(batch_size): n = caffe.NetSpec() n.data, n.label = L.DummyData(shape=[dict(dim=[batch_size, 1, 28, 28]), dict(dim=[batch_size, 1, 1, 1])], ...
3,756
40.744444
80
py
Stochastic-Quantization
Stochastic-Quantization-master/caffe/python/caffe/test/test_python_layer.py
import unittest import tempfile import os import six import caffe class SimpleLayer(caffe.Layer): """A layer that just multiplies by ten""" def setup(self, bottom, top): pass def reshape(self, bottom, top): top[0].reshape(*bottom[0].data.shape) def forward(self, bottom, top): ...
5,510
31.609467
81
py
Stochastic-Quantization
Stochastic-Quantization-master/caffe/scripts/cpp_lint.py
#!/usr/bin/env python # # Copyright (c) 2009 Google Inc. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above copyright # notice, this list...
187,569
37.483792
93
py
Stochastic-Quantization
Stochastic-Quantization-master/caffe/scripts/split_caffe_proto.py
#!/usr/bin/env python import mmap import re import os import errno script_path = os.path.dirname(os.path.realpath(__file__)) # a regex to match the parameter definitions in caffe.proto r = re.compile(r'(?://.*\n)*message ([^ ]*) \{\n(?: .*\n|\n)*\}') # create directory to put caffe.proto fragments try: os.mkdir(...
941
25.166667
65
py
Stochastic-Quantization
Stochastic-Quantization-master/caffe/scripts/download_model_binary.py
#!/usr/bin/env python import os import sys import time import yaml import hashlib import argparse from six.moves import urllib required_keys = ['caffemodel', 'caffemodel_url', 'sha1'] def reporthook(count, block_size, total_size): """ From http://blog.moleculea.com/2012/10/04/urlretrieve-progres-indicator/ ...
2,531
31.461538
78
py
P-STMO
P-STMO-main/run_3dhp.py
import os import glob import torch import random import logging import numpy as np from tqdm import tqdm import torch.nn as nn import torch.utils.data import torch.optim as optim from common.opt import opts from common.utils import * from common.camera import get_uvd2xyz from common.load_data_3dhp_mae import Fusion fro...
16,320
38.233173
170
py
P-STMO
P-STMO-main/run.py
import os import glob import torch import random import logging import numpy as np from tqdm import tqdm import torch.nn as nn import torch.utils.data import torch.optim as optim from common.opt import opts from common.utils import * from common.camera import get_uvd2xyz from common.load_data_hm36_tds import Fusion fro...
15,226
37.745547
168
py
P-STMO
P-STMO-main/run_in_the_wild.py
import os import glob import torch import random import logging import numpy as np from tqdm import tqdm import torch.nn as nn import torch.utils.data import torch.optim as optim from common.opt import opts from common.utils import * from common.camera import get_uvd2xyz from common.load_data_hm36_tds_in_the_wild impor...
15,554
37.790524
168
py
P-STMO
P-STMO-main/common/load_data_hm36_tds_in_the_wild.py
import torch.utils.data as data import numpy as np from common.utils import deterministic_random from common.camera import world_to_camera, normalize_screen_coordinates from common.generator_tds import ChunkedGenerator class Fusion(data.Dataset): def __init__(self, opt, dataset, root_path, train=True, MAE=False,...
9,334
50.291209
128
py
P-STMO
P-STMO-main/common/load_data_3dhp_mae.py
import torch.utils.data as data import numpy as np from common.utils import deterministic_random from common.camera import world_to_camera, normalize_screen_coordinates from common.generator_3dhp import ChunkedGenerator class Fusion(data.Dataset): def __init__(self, opt, root_path, train=True, MAE=False): ...
9,051
45.420513
125
py
P-STMO
P-STMO-main/common/camera.py
import sys import numpy as np import torch def normalize_screen_coordinates(X, w, h): assert X.shape[-1] == 2 return X / w * 2 - [1, h / w] def image_coordinates(X, w, h): assert X.shape[-1] == 2 # Reverse camera frame normalization return (X + [1, h / w]) * w / 2 def world_to_camera(X, R, t): Rt = ...
2,451
25.652174
87
py
P-STMO
P-STMO-main/common/utils.py
import torch import numpy as np import hashlib from torch.autograd import Variable import os def deterministic_random(min_value, max_value, data): digest = hashlib.sha256(data.encode()).digest() raw_value = int.from_bytes(digest[:4], byteorder='little', signed=False) return int(raw_value / (2 ** 32 - 1...
7,304
31.039474
118
py
P-STMO
P-STMO-main/common/opt.py
import argparse import os import math import time import torch class opts(): def __init__(self): self.parser = argparse.ArgumentParser() def init(self): self.parser.add_argument('--layers', default=3, type=int) self.parser.add_argument('--channel', default=256, type=int) self.p...
5,367
42.290323
94
py
P-STMO
P-STMO-main/common/load_data_hm36_tds.py
import torch.utils.data as data import numpy as np from common.utils import deterministic_random from common.camera import world_to_camera, normalize_screen_coordinates from common.generator_tds import ChunkedGenerator class Fusion(data.Dataset): def __init__(self, opt, dataset, root_path, train=True, MAE=False,...
9,325
50.241758
128
py
P-STMO
P-STMO-main/in_the_wild/videopose_PSTMO.py
import os import time from common.arguments import parse_args from common.camera import * from common.generators import * from common.loss import * from common.model import * from common.utils import Timer, evaluate, add_path from common.inference_3d import * from model.block.refine import refine from model.stmo impo...
7,170
35.217172
139
py
P-STMO
P-STMO-main/in_the_wild/inference_3d.py
# Copyright (c) 2018-present, Facebook, Inc. # All rights reserved. # # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. # import hashlib import os import pathlib import shutil import sys import time import cv2 import numpy as np import torch from to...
3,586
32.523364
128
py
P-STMO
P-STMO-main/model/stmo.py
import torch import torch.nn as nn from model.block.vanilla_transformer_encoder import Transformer from model.block.strided_transformer_encoder import Transformer as Transformer_reduce class Linear(nn.Module): def __init__(self, linear_size, p_dropout=0.25): super(Linear, self).__init__() self.l_si...
4,047
30.874016
92
py
P-STMO
P-STMO-main/model/stmo_pretrain.py
import torch import torch.nn as nn from model.block.vanilla_transformer_encoder_pretrain import Transformer, Transformer_dec from model.block.strided_transformer_encoder import Transformer as Transformer_reduce import numpy as np class LayerNorm(nn.Module): def __init__(self, features, eps=1e-6): super(Lay...
5,518
32.652439
119
py
P-STMO
P-STMO-main/model/block/refine.py
import torch import torch.nn as nn from torch.autograd import Variable fc_out = 256 fc_unit = 1024 class refine(nn.Module): def __init__(self, opt): super().__init__() out_seqlen = 1 fc_in = opt.out_channels*2*out_seqlen*opt.n_joints fc_out = opt.in_channels * opt.n_joints ...
948
24.648649
89
py
P-STMO
P-STMO-main/model/block/vanilla_transformer_encoder_pretrain.py
import torch import torch.nn as nn import torch.nn.functional as F from torch.autograd import Variable import numpy as np import math import os import copy def clones(module, N): return nn.ModuleList([copy.deepcopy(module) for _ in range(N)]) class Encoder(nn.Module): def __init__(self, layer, N): sup...
5,115
31.176101
98
py
P-STMO
P-STMO-main/model/block/strided_transformer_encoder.py
import torch import torch.nn as nn import torch.nn.functional as F from torch.autograd import Variable import numpy as np import math import os import copy def clones(module, N): return nn.ModuleList([copy.deepcopy(module) for _ in range(N)]) class Encoder(nn.Module): def __init__(self, layer, N, length, d_mo...
5,685
32.05814
120
py
P-STMO
P-STMO-main/model/block/vanilla_transformer_encoder.py
import torch import torch.nn as nn import torch.nn.functional as F from torch.autograd import Variable import numpy as np import math import os import copy def clones(module, N): return nn.ModuleList([copy.deepcopy(module) for _ in range(N)]) class Encoder(nn.Module): def __init__(self, layer, N): sup...
4,191
30.283582
98
py
InvariantRuleAD
InvariantRuleAD-main/core/model/reconstruction_models/DeepSVDD.py
import numpy as np import tensorflow as tf from tensorflow import keras import tempfile from .. import BaseModel import random def oneclass_loss(z,radius,nu): dist = tf.reduce_sum(tf.square(z), axis=-1) loss = tf.maximum(dist - radius ** 2, tf.zeros_like(dist)) loss = radius**2+(1/nu)*tf.reduce_mean(loss)...
4,639
32.623188
113
py
InvariantRuleAD
InvariantRuleAD-main/core/model/reconstruction_models/vanilla_autoencoder.py
from tensorflow import keras import tensorflow as tf import numpy as np import tempfile import random from .. import BaseModel,AnomalyDetector from ...preprocessing.signals import ContinuousSignal,CategoricalSignal from ...learning.hp_optimization.Hyperparameter import ConstHyperparameter,UniformIntegerHyperparameter f...
10,613
35.854167
153
py
InvariantRuleAD
InvariantRuleAD-main/core/preprocessing/data_handler.py
import numpy as np import tensorflow as tf import matplotlib.pyplot as plt import warnings from builtins import isinstance class TSAEDataHandler(): ''' Data Handler for time-series autoencoders Parameters ---------- sequence_length : int the length of sequence feats : list of stri...
11,215
34.381703
120
py
CLUE
CLUE-master/baselines/models/xlnet/data_utils.py
# -*- coding: utf-8 -*- from __future__ import absolute_import from __future__ import division from __future__ import print_function import json import os import random from absl import flags import absl.logging as _logging # pylint: disable=unused-import import numpy as np import tensorflow as tf from prepro_u...
29,915
31.659389
97
py
CLUE
CLUE-master/baselines/models_pytorch/classifier_pytorch/run_classifier.py
# -*- coding: utf-8 -*- # @Author: bo.shi # @Date: 2019-12-30 19:26:53 # @Last Modified by: bo.shi # @Last Modified time: 2019-12-31 19:49:36 """ Finetuning the library models for sequence classification on CLUE (Bert, ERNIE, XLNet, RoBERTa).""" from __future__ import absolute_import, division, print_function imp...
31,505
54.273684
152
py
CLUE
CLUE-master/baselines/models_pytorch/classifier_pytorch/convert_albert_original_tf_checkpoint_to_pytorch.py
"""Convert ALBERT checkpoint.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import argparse import torch from transformers.modeling_albert import BertConfig, AlbertForPreTraining, load_tf_weights_in_albert import logging logging.basicConfig(level=log...
2,388
40.189655
110
py
CLUE
CLUE-master/baselines/models_pytorch/classifier_pytorch/convert_ernie_original_pad_checkpoint_to_pytorch.py
#!/usr/bin/env python # encoding: utf-8 """ File Description: https://github.com/nghuyong/ERNIE-Pytorch Author: nghuyong Mail: nghuyong@163.com Created Time: 2020/7/14 """ import collections import os import json import shutil import paddle.fluid.dygraph as D import torch from paddle import fluid # downloading paddle...
5,179
52.958333
118
py
CLUE
CLUE-master/baselines/models_pytorch/classifier_pytorch/convert_bert_original_tf_checkpoint_to_pytorch.py
"""Convert BERT checkpoint.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import argparse import torch from transformers import BertConfig, BertForPreTraining, load_tf_weights_in_bert import logging logging.basicConfig(level=logging.INFO) def conver...
1,972
36.942308
101
py
CLUE
CLUE-master/baselines/models_pytorch/classifier_pytorch/convert_xlnet_original_tf_checkpoint_to_pytorch.py
"""Convert XLNET checkpoint.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import os import argparse import torch from transformers import (CONFIG_NAME, WEIGHTS_NAME, XLNetConfig, XLNetLMHeadModel, ...
2,480
39.016129
104
py
CLUE
CLUE-master/baselines/models_pytorch/classifier_pytorch/tools/common.py
import os import random import torch import numpy as np import json import pickle import torch.nn as nn from collections import OrderedDict from pathlib import Path import logging logger = logging.getLogger() def print_config(config): info = "Running with the following configs:\n" for k, v in config.items(): ...
11,484
28.677003
128
py
CLUE
CLUE-master/baselines/models_pytorch/classifier_pytorch/processors/clue.py
# -*- coding: utf-8 -*- # @Author: bo.shi # @Date: 2019-12-30 19:26:53 # @Last Modified by: bo.shi # @Last Modified time: 2020-01-01 11:39:23 """ CLUE processors and helpers """ import logging import os import torch from .utils import DataProcessor, InputExample, InputFeatures logger = logging.getLogger(__name__)...
20,143
38.114563
130
py
CLUE
CLUE-master/baselines/models_pytorch/classifier_pytorch/transformers/optimization.py
# coding=utf-8 # Copyright 2018 The Google AI Language Team Authors and The HuggingFace Inc. team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICEN...
8,635
44.452632
130
py
CLUE
CLUE-master/baselines/models_pytorch/classifier_pytorch/transformers/__main__.py
# coding: utf8 def main(): import sys if (len(sys.argv) < 4 or len(sys.argv) > 6) or sys.argv[1] not in ["bert", "gpt", "transfo_xl", "gpt2", "xlnet", "xlm"]: print( "This command line utility let you convert original (author released) model checkpoint to pytorch.\n" "It should be used a...
7,082
53.484615
135
py
CLUE
CLUE-master/baselines/models_pytorch/classifier_pytorch/transformers/configuration_utils.py
# coding=utf-8 # Copyright 2018 The Google AI Language Team Authors and The HuggingFace Inc. team. # Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a cop...
10,772
50.793269
296
py
CLUE
CLUE-master/baselines/models_pytorch/classifier_pytorch/transformers/modeling_distilbert.py
# coding=utf-8 # Copyright 2019-present, the HuggingFace Inc. team, The Google AI Language Team and Facebook, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.or...
34,864
49.237752
201
py
CLUE
CLUE-master/baselines/models_pytorch/classifier_pytorch/transformers/modeling_utils.py
# coding=utf-8 # Copyright 2018 The Google AI Language Team Authors and The HuggingFace Inc. team. # Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a cop...
43,409
52.06846
472
py
CLUE
CLUE-master/baselines/models_pytorch/classifier_pytorch/transformers/modeling_bert.py
# coding=utf-8 # Copyright 2018 The Google AI Language Team Authors and The HuggingFace Inc. team. # Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a cop...
59,643
50.864348
187
py
CLUE
CLUE-master/baselines/models_pytorch/classifier_pytorch/transformers/modeling_gpt2.py
# coding=utf-8 # Copyright 2018 The OpenAI Team Authors and HuggingFace Inc. team. # Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License...
33,126
48.965309
148
py
CLUE
CLUE-master/baselines/models_pytorch/classifier_pytorch/transformers/modeling_openai.py
# coding=utf-8 # Copyright 2018 The OpenAI Team Authors and HuggingFace Inc. team. # Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License...
30,836
48.57717
148
py
CLUE
CLUE-master/baselines/models_pytorch/classifier_pytorch/transformers/tokenization_bert.py
# coding=utf-8 # Copyright 2018 The Google AI Language Team Authors and The HuggingFace Inc. team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICEN...
22,451
43.636183
183
py
CLUE
CLUE-master/baselines/models_pytorch/classifier_pytorch/transformers/configuration_ctrl.py
# coding=utf-8 # Copyright 2018 Salesforce and HuggingFace Inc. team. # Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # htt...
5,775
39.111111
120
py
CLUE
CLUE-master/baselines/models_pytorch/classifier_pytorch/transformers/file_utils.py
""" Utilities for working with the local dataset cache. This file is adapted from the AllenNLP library at https://github.com/allenai/allennlp Copyright by the AllenNLP authors. """ from __future__ import (absolute_import, division, print_function, unicode_literals) import sys import json import logging import os impor...
11,622
34.763077
144
py
CLUE
CLUE-master/baselines/models_pytorch/classifier_pytorch/transformers/__init__.py
__version__ = "2.1.1" # Work around to update TensorFlow's absl.logging threshold which alters the # default Python logging output behavior when present. # see: https://github.com/abseil/abseil-py/issues/99 # and: https://github.com/tensorflow/tensorflow/issues/26691#issuecomment-500369493 try: import absl.logging...
5,761
58.402062
109
py
CLUE
CLUE-master/baselines/models_pytorch/classifier_pytorch/transformers/modeling_transfo_xl.py
# coding=utf-8 # Copyright 2018 Google AI, Google Brain and Carnegie Mellon University Authors and the HuggingFace Inc. team. # Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the Lice...
39,657
43.50954
157
py
CLUE
CLUE-master/baselines/models_pytorch/classifier_pytorch/transformers/modeling_albert.py
# coding=utf-8 # Copyright 2018 The Google AI Language Team Authors and The HuggingFace Inc. team. # Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a cop...
54,163
49.810507
153
py