repo
stringlengths
2
99
file
stringlengths
13
225
code
stringlengths
0
18.3M
file_length
int64
0
18.3M
avg_line_length
float64
0
1.36M
max_line_length
int64
0
4.26M
extension_type
stringclasses
1 value
tensorsketch
tensorsketch-master/tensorsketch/temp.py
def f(x, y, **kwargs): print(f"{x}->{kwargs['var1']}") # f(1,2, **{'var1':10, 'var2':20}) def g(**kwargs): a = kwargs f(100, 2, **a) g(**{'var1':10})
166
12.916667
35
py
tensorsketch
tensorsketch-master/tensorsketch/util.py
import numpy as np from scipy import fftpack import tensorly as tl from tensorly.base import unfold, fold from scipy.sparse.linalg import svds from collections.abc import Iterable tl.set_backend('numpy') def random_matrix_generator(m, n, Rinfo_bucket): ''' Generate random matrix of size m x n :param m:...
10,216
35.230496
133
py
tensorsketch
tensorsketch-master/tensorsketch/__init__.py
name = "tensorsketch"
22
10.5
21
py
tensorsketch
tensorsketch-master/tensorsketch/sketch.py
import tensorly as tl import numpy as np from .util import random_matrix_generator, square_tensor_gen from .util import ssrft_modeprod, gprod, sp0prod from .random_projection import random_matrix_generator, tensor_random_matrix_generator from sklearn.decomposition import TruncatedSVD def fetch_arm_sketch(X, ks, tenso...
2,591
31.810127
86
py
tensorsketch
tensorsketch-master/tensorsketch/tensor_approx.py
####################### # * # Yiming Sun * # 11/2019 * # * ####################### import numpy as np from scipy import fftpack import tensorly as tl from .util import square_tensor_gen, st_hosvd from .sketch import fetch_arm_sketch, fetch_core_sketch import...
8,797
38.809955
126
py
tensorsketch
tensorsketch-master/tensorsketch/tests/test_tucker.py
import numpy as np from scipy import fftpack import tensorly as tl from unittest import TestCase from ..util import square_tensor_gen, TensorInfoBucket, RandomInfoBucket, eval_rerr from ..sketch import Sketch import time from tensorly.decomposition import tucker from ..recover_from_sketches import SketchTwoPassRecover...
1,368
30.837209
93
py
tensorsketch
tensorsketch-master/tensorsketch/tests/test_tensor_recover.py
import numpy as np from scipy import fftpack import tensorly as tl from unittest import TestCase from ..util import * from ..sketch import * import time from tensorly.decomposition import tucker from ..recover_from_sketches import SketchTwoPassRecover from ..recover_from_sketches import SketchOnePassRecover from sklea...
1,772
39.295455
89
py
deep_gen_msm
deep_gen_msm-master/prinz/deep_ml_0.py
import torch import torch.nn as nn from torch.autograd import Variable, grad, backward import torch.nn.functional as F import numpy as np import matplotlib.pyplot as plt from scipy.stats import norm import torch.utils.data as Data from math import pi,inf,log import copy from pyemma.plots import scatter_contour from py...
9,513
33.471014
146
py
deep_gen_msm
deep_gen_msm-master/prinz/deep_ed_0.py
import torch import torch.nn as nn from torch.autograd import Variable, grad, backward import torch.nn.functional as F import numpy as np import matplotlib.pyplot as plt from scipy.stats import norm import torch.utils.data as Data from math import pi,inf,log import copy from pyemma.plots import scatter_contour from py...
11,120
37.085616
166
py
HPLFlowNet
HPLFlowNet-master/main.py
import os, sys import os.path as osp import time from functools import partial import gc import traceback import numpy as np import torch import torch.nn.parallel import torch.backends.cudnn as cudnn import torch.optim import torch.utils.data import transforms import datasets import models import cmd_args from main_...
10,414
34.790378
99
py
HPLFlowNet
HPLFlowNet-master/visualization.py
# Usage: python xxx.py path_to_pc1/pc2/output/epe3d/path_list [pc2] import numpy as np import sys import mayavi.mlab as mlab import os.path as osp import pickle SCALE_FACTOR = 0.05 MODE = 'sphere' DRAW_LINE = True if '-h' in ' '.join(sys.argv): print('Usage: python3 visu_new.py VISU_PATH') sys.exit(0) visu_path =...
2,870
25.831776
121
py
HPLFlowNet
HPLFlowNet-master/main_utils.py
# helper functions for training import os, sys import shutil import torch from torch.nn import init def reset_learning_rate(optimizer, args): for param_group in optimizer.param_groups: param_group['lr'] = args.lr def adjust_learning_rate(optimizer, epoch, args): # old_lr = optimizer.param_groups[0]...
4,763
30.342105
98
py
HPLFlowNet
HPLFlowNet-master/cmd_args.py
import socket import numpy as np import yaml import os, sys import os.path as osp import datasets import models from utils.easydict import EasyDict model_names = sorted(name for name in models.__dict__ if (not name.startswith("__")) and ('Args' not in name) ...
2,192
32.227273
111
py
HPLFlowNet
HPLFlowNet-master/evaluation_utils.py
import numpy as np def evaluate_3d(sf_pred, sf_gt): """ sf_pred: (N, 3) sf_gt: (N, 3) """ l2_norm = np.linalg.norm(sf_gt - sf_pred, axis=-1) EPE3D = l2_norm.mean() sf_norm = np.linalg.norm(sf_gt, axis=-1) relative_err = l2_norm / (sf_norm + 1e-4) acc3d_strict = (np.logical_or(l2_...
1,018
26.540541
95
py
HPLFlowNet
HPLFlowNet-master/evaluation_bnn.py
import os, sys import os.path as osp import numpy as np import pickle import torch import torch.optim import torch.utils.data from main_utils import * from utils import geometry from evaluation_utils import evaluate_2d, evaluate_3d TOTAL_NUM_SAMPLES = 0 def evaluate(val_loader, model, logger, args): save_idx =...
4,786
36.108527
90
py
HPLFlowNet
HPLFlowNet-master/models/HPLFlowNet.py
import torch import torch.nn as nn from .bilateralNN import BilateralConvFlex from .bnn_flow import BilateralCorrelationFlex from .module_utils import Conv1dReLU __all__ = ['HPLFlowNet'] class HPLFlowNet(nn.Module): def __init__(self, args): super(HPLFlowNet, self).__init__() self.scales_filter_...
25,890
59.071926
117
py
HPLFlowNet
HPLFlowNet-master/models/HPLFlowNet_shallow.py
import torch import torch.nn as nn from .bilateralNN import BilateralConvFlex from .bnn_flow import BilateralCorrelationFlex from .module_utils import Conv1dReLU __all__ = ['HPLFlowNetShallow'] class HPLFlowNetShallow(nn.Module): def __init__(self, args): super(HPLFlowNetShallow, self).__init__() ...
18,315
57.705128
117
py
HPLFlowNet
HPLFlowNet-master/models/bilateralNN.py
import torch import torch.nn as nn from .module_utils import Conv2dReLU DELETE_TMP_VARIABLES = False class SparseSum(torch.autograd.Function): @staticmethod def forward(ctx, indices, values, size, cuda): """ :param ctx: :param indices: (1, B*d1*N) :param values: (B*d1*N, fea...
10,021
40.933054
116
py
HPLFlowNet
HPLFlowNet-master/models/bnn_flow.py
import torch import torch.nn as nn from .bilateralNN import sparse_sum from .module_utils import Conv2dReLU, Conv3dReLU DELETE_TMP_VARIABLES = False class BilateralCorrelationFlex(nn.Module): def __init__(self, d, corr_filter_radius, corr_corr_radius, num_input, num_corr_output...
9,641
44.267606
120
py
HPLFlowNet
HPLFlowNet-master/models/epe3d_loss.py
import torch import torch.nn as nn class EPE3DLoss(nn.Module): def __init__(self): super(EPE3DLoss, self).__init__() def forward(self, input, target): return torch.norm(input - target, p=2, dim=1)
223
21.4
53
py
HPLFlowNet
HPLFlowNet-master/models/__init__.py
from .epe3d_loss import * from .HPLFlowNet import * from .HPLFlowNet_shallow import *
87
16.6
33
py
HPLFlowNet
HPLFlowNet-master/models/build_khash_cffi.py
import glob import os from cffi import FFI # include_dirs = [os.path.join('libraries', 'Rmath', 'src'), # os.path.join('libraries', 'Rmath', 'include')] # rmath_src = glob.glob(os.path.join('libraries', 'Rmath', 'src', '*.c')) ffi = FFI() ffi.set_source('_khash_ffi', '#include "khash_int2int.h"') ...
653
24.153846
73
py
HPLFlowNet
HPLFlowNet-master/models/module_utils.py
import torch import torch.nn as nn __all__ = ['Conv1dReLU', 'Conv2dReLU', 'Conv3dReLU'] LEAKY_RATE = 0.1 class Conv1dReLU(nn.Module): def __init__(self, in_channels, out_channels, kernel_size=1, stride=1, padding=0, use_leaky=False, bias=True): super(Conv1dReLU, self).__init__() self.in_channels...
2,027
31.190476
117
py
HPLFlowNet
HPLFlowNet-master/datasets/kitti.py
import sys, os import os.path as osp import numpy as np import torch.utils.data as data __all__ = ['KITTI'] class KITTI(data.Dataset): """ Args: train (bool): If True, creates dataset from training set, otherwise creates from test set. transform (callable): gen_func (callable): ...
3,701
33.277778
105
py
HPLFlowNet
HPLFlowNet-master/datasets/flyingthings3d_subset.py
import sys, os import os.path as osp import numpy as np import torch.utils.data as data __all__ = ['FlyingThings3DSubset'] class FlyingThings3DSubset(data.Dataset): """ Args: train (bool): If True, creates dataset from training set, otherwise creates from test set. transform (callable): ...
3,536
33.676471
120
py
HPLFlowNet
HPLFlowNet-master/datasets/__init__.py
from .flyingthings3d_subset import * from .kitti import *
58
18.666667
36
py
HPLFlowNet
HPLFlowNet-master/data_preprocess/process_flyingthings3d_subset.py
import numpy as np import sys, os import os.path as osp from multiprocessing import Pool import argparse import IO from flyingthings3d_utils import * parser = argparse.ArgumentParser() parser.add_argument('--raw_data_path', type=str, help="path to the raw data") parser.add_argument('--save_path', type=str, help="save...
2,962
36.506329
116
py
HPLFlowNet
HPLFlowNet-master/data_preprocess/flyingthings3d_utils.py
import numpy as np def next_pixel2pc(flow, disparity, save_path=None, f=-1050., cx=479.5, cy=269.5): height, width = disparity.shape BASELINE = 1.0 depth = -1. * f * BASELINE / disparity x = ((np.tile(np.arange(width, dtype=np.float32)[None, :], (height, 1)) - cx + flow[..., 0]) * -1. / disparity)[:...
1,143
33.666667
118
py
HPLFlowNet
HPLFlowNet-master/data_preprocess/process_kitti.py
import os, sys import os.path as osp import numpy as np from multiprocessing import Pool from kitti_utils import * calib_root = './utils/calib_cam_to_cam/' data_root = sys.argv[1] disp1_root = osp.join(data_root, 'training/disp_occ_0') disp2_root = osp.join(data_root, 'training/disp_occ_1') op_flow_root = osp.join(da...
2,644
31.256098
96
py
HPLFlowNet
HPLFlowNet-master/data_preprocess/IO.py
#!/usr/bin/env python3.4 import os import re import numpy as np import uuid from scipy import misc import numpy as np from PIL import Image import sys def read(file): if file.endswith('.float3'): return readFloat(file) elif file.endswith('.flo'): return readFlow(file) elif file.endswith('.ppm'): return r...
5,244
26.898936
92
py
HPLFlowNet
HPLFlowNet-master/data_preprocess/python_pfm.py
import re import numpy as np import sys def readPFM(file): file = open(file, 'rb') color = None width = None height = None scale = None endian = None header = file.readline().rstrip() if header == 'PF': color = True elif header == 'Pf': color = False else: ...
1,721
22.916667
92
py
HPLFlowNet
HPLFlowNet-master/data_preprocess/kitti_utils.py
import numpy as np import png def pixel2xyz(depth, P_rect, px=None, py=None): assert P_rect[0,1] == 0 assert P_rect[1,0] == 0 assert P_rect[2,0] == 0 assert P_rect[2,1] == 0 assert P_rect[0,0] == P_rect[1,1] focal_length_pixel = P_rect[0,0] height, width = depth.shape[:2] if px is...
1,904
29.238095
82
py
HPLFlowNet
HPLFlowNet-master/utils/easydict.py
class EasyDict(dict): """ Get attributes >>> d = EasyDict({'foo':3}) >>> d['foo'] 3 >>> d.foo 3 >>> d.bar Traceback (most recent call last): ... AttributeError: 'EasyDict' object has no attribute 'bar' >>> #Works recursively >>> d = EasyDict({'foo':3, 'bar':{'x':1, 'y...
2,438
23.148515
79
py
HPLFlowNet
HPLFlowNet-master/utils/geometry.py
import numpy as np import os import os.path as osp def get_batch_2d_flow(pc1, pc2, predicted_pc2, paths): if 'KITTI' in paths[0] or 'kitti' in paths[0]: focallengths = [] cxs = [] cys = [] constx = [] consty = [] constz = [] for path in paths: fn...
2,600
38.409091
103
py
HPLFlowNet
HPLFlowNet-master/utils/__init__.py
0
0
0
py
HPLFlowNet
HPLFlowNet-master/transforms/functional.py
import torch def to_tensor(array): """Convert a 2D `numpy.ndarray`` to tensor, do transpose first. See ``ToTensor`` for more details. Args: array (numpy.ndarray): Image to be converted to tensor. Returns: Tensor: Converted image. """ assert len(array.shape) == 2 array = a...
381
18.1
67
py
HPLFlowNet
HPLFlowNet-master/transforms/__init__.py
from .transforms import *
26
12.5
25
py
HPLFlowNet
HPLFlowNet-master/transforms/transforms.py
import os, sys import os.path as osp from collections import defaultdict import numbers import math import numpy as np import traceback import time import torch import numba from numba import njit, cffi_support from . import functional as F sys.path.append(osp.join(osp.dirname(osp.dirname(osp.abspath(__file__))), '...
29,266
43.010526
127
py
fact-checkers-fact-check
fact-checkers-fact-check-main/analyses/utils.py
from tempfile import NamedTemporaryFile from matplotlib.image import imread def get_size(fig, dpi=100): with NamedTemporaryFile(suffix='.png') as f: fig.savefig(f.name, bbox_inches='tight', dpi=dpi) height, width, _channels = imread(f.name).shape return width / dpi, height / dpi def set...
1,131
38.034483
92
py
arx
arx-master/setup.py
"""ARX paper code Confidential code not for distribution. Alex Cooper <alex@acooper.org> """ from codecs import open from os import path from setuptools import find_packages, setup here = path.abspath(path.dirname(__file__)) # Get the long description from the README file with open(path.join(here, "README.md"), enc...
1,311
25.24
66
py
arx
arx-master/arx/cv.py
import chex import jax.numpy as jnp class CVScheme: """Generic CV scheme class Methods: name: name of the scheme suitable for plots and output n_folds: number of folds, always numbered from 0 test_mask: boolean mask for test data for fold i train_mask: boolean mask for train ...
5,192
26.331579
92
py
arx
arx-master/arx/sarx_test.py
import unittest import cv import jax.numpy as jnp from sarx import * class TestSARX(unittest.TestCase): def setUp(self) -> None: self.T = 100 self.phi_star = jnp.array([0.4]) self.sigsq_star = 1.5 self.beta_star = jnp.array([1.0, 2.0, 0.5]) self.Z = make_Z(q=3, T=self.T, p...
9,344
38.935897
88
py
arx
arx-master/arx/sarx_experiments.py
import jax.numpy as jnp import pandas as pd from arx.cv import * from arx.experiments import * from arx.sarx import * def by_excluded_effect(filename, ex_no: int, variant: str, T: int = 100, seed: int = 0): """Simplified model selection experiment, varying beta2 (the excluded effect) Args: filename:...
26,848
41.149137
136
py
arx
arx-master/arx/sarx.py
from typing import Tuple import chex import jax from jax import numpy as jnp from jax.numpy.linalg import inv, slogdet, solve from jax.scipy.linalg import solve_triangular from jax.scipy.stats import multivariate_normal from scipy import optimize from arx.arx import make_L from arx.cv import CVScheme class Poly: ...
17,979
35.470588
97
py
arx
arx-master/arx/experiments.py
from typing import Any, Callable, Dict import jax.numpy as jnp from chex import Array, PRNGKey import numpy as np import os import jax import chex from arx import sarx, arx EFFECT_SIZES = jnp.array([0.0, 0.5, 1.0, 2.0, 5.0, 10.0]) # \beta_*^{easy} EASY_EFFECTS = jnp.array([1.0, 2.0, 1.0]) # \beta_*^{hard} HARD_EFFE...
6,039
25.964286
73
py
arx
arx-master/arx/arx_test.py
from jax.config import config config.update("jax_enable_x64", True) import unittest import cv import jax import jax.numpy as jnp from chex import assert_equal, assert_shape, assert_tree_all_finite from scipy.integrate import quad import arx class TestArx(unittest.TestCase): def setUp(self) -> None: ke...
9,391
32.070423
82
py
arx
arx-master/arx/cv_test.py
import unittest import cv from chex import assert_equal, assert_shape, assert_tree_all_close from jax import numpy as jnp from tree import assert_same_structure class TestCVSchemes(unittest.TestCase): def test_loo(self): loo = cv.LOOCVScheme(120) assert_equal(loo.n_folds(), 120) tstm = jn...
2,115
37.472727
82
py
arx
arx-master/arx/cli.py
#!.venv/bin/python3 from jax.config import config config.update("jax_enable_x64", True) import glob import os import pandas as pd import click import arx.arx_experiments as arxex import arx.sarx_experiments as sarxex RESULTS = 'results' def ensure_results_dir(): if not os.path.exists(RESULTS): os.mkd...
12,401
44.933333
156
py
arx
arx-master/arx/arx_experiments.py
from typing import List import click import jax import pandas as pd import arx.experiments as ex from arx import cv def full_bayes( experiment_no: int, experiment_variant: str, filename: str, T: int = 100, alternative: str = '10-fold', n_posts=10, mc_reps=500, n_warmup=400, n_cha...
9,112
39.323009
137
py
arx
arx-master/arx/arx.py
"""Full ARX(p,q) model, using quadrature for inference. This limited first version can only do inference for p=1, but can simulate from any ARX(p,q) dgp. """ f"This script needs python 3.x" from jax.config import config from arx.cv import CVScheme config.update("jax_enable_x64", True) from collections import nam...
38,201
35.732692
127
py
arx
arx-master/arx/experiments_test.py
import os import unittest import experiments as ex import jax import sarx_experiments as sx import arx class TestExperimentInstance(unittest.TestCase): def setUp(self) -> None: self.ex1 = ex.make_full_experiment(1, "hard", simplified=False) def test_experiment_instance(self) -> None: key = ...
2,784
30.647727
87
py
ADaPTION
ADaPTION-master/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
ADaPTION
ADaPTION-master/tools/extra/extract_seconds.py
#!/usr/bin/env python import datetime import os import sys def extract_datetime_from_line(line, year): # Expected format: I0210 13:39:22.381027 25210 solver.cpp:204] Iteration 100, lr = 0.00992565 line = line.strip().split() month = int(line[0][1:3]) day = int(line[0][3:]) timestamp = line[1] p...
1,966
29.261538
97
py
ADaPTION
ADaPTION-master/tools/extra/resize_and_crop_images.py
#!/usr/bin/env python from mincepie import mapreducer, launcher import gflags import os import cv2 from PIL import Image # gflags gflags.DEFINE_string('image_lib', 'opencv', 'OpenCV or PIL, case insensitive. The default value is the faster OpenCV.') gflags.DEFINE_string('input_folder', '', ...
4,541
40.290909
99
py
ADaPTION
ADaPTION-master/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...
6,688
32.613065
86
py
ADaPTION
ADaPTION-master/examples/create_prototxt/create_prototxt.py
import collections as c base_dir = './' layer_dir = base_dir + 'layers/' # lp = False # use lp version of the layers lp = True # use lp version of the layers # deploy = False deploy = True visualize = False # visualize = True # VGG 16 # net_descriptor = ['64C3S1', 'A', 'ReLU', '64C3S1', 'A', 'ReLU', '2P2', # ...
25,917
58.718894
169
py
ADaPTION
ADaPTION-master/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
ADaPTION
ADaPTION-master/examples/web_demo/exifutil.py
""" This script handles the skimage exif problem. """ from PIL import Image import numpy as np ORIENTATIONS = { # used in apply_orientation 2: (Image.FLIP_LEFT_RIGHT,), 3: (Image.ROTATE_180,), 4: (Image.FLIP_TOP_BOTTOM,), 5: (Image.FLIP_LEFT_RIGHT, Image.ROTATE_90), 6: (Image.ROTATE_270,), 7...
1,046
25.175
51
py
ADaPTION
ADaPTION-master/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
ADaPTION
ADaPTION-master/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
ADaPTION
ADaPTION-master/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
ADaPTION
ADaPTION-master/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
ADaPTION
ADaPTION-master/examples/low_precision/imagenet/visualization/Visualization_weights.py
import caffe import matplotlib.pyplot as plt import numpy as np from collections import defaultdict plt.rcParams['font.size'] = 20 # plt.rcParams['xtick.labelzie'] = 18 def make_2d(data): return np.reshape(data, (data.shape[0], -1)) caffe.set_mode_gpu() caffe.set_device(0) caffe_root = '/home/moritz/Repositori...
19,380
31.463987
98
py
ADaPTION
ADaPTION-master/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
ADaPTION
ADaPTION-master/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
ADaPTION
ADaPTION-master/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
ADaPTION
ADaPTION-master/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
ADaPTION
ADaPTION-master/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
ADaPTION
ADaPTION-master/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,048
34.45815
88
py
ADaPTION
ADaPTION-master/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
ADaPTION
ADaPTION-master/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
ADaPTION
ADaPTION-master/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
ADaPTION
ADaPTION-master/python/caffe/__init__.py
from .pycaffe import Net, SGDSolver, NesterovSolver, AdaGradSolver, RMSPropSolver, AdaDeltaSolver, AdamSolver from ._caffe import set_mode_cpu, set_mode_gpu, set_device, Layer, get_solver, layer_type_list, set_random_seed from ._caffe import __version__ from .proto.caffe_pb2 import TRAIN, TEST from .classifier import C...
434
47.333333
111
py
ADaPTION
ADaPTION-master/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,243
32.564179
89
py
ADaPTION
ADaPTION-master/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,813
34.97551
120
py
ADaPTION
ADaPTION-master/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,729
32.151042
110
py
ADaPTION
ADaPTION-master/python/caffe/nullhop/caffe2nullhop.py
''' TODO: remove pixels from the network file TODO: support different fixed point representations other than q7.8 TODO: check kernels arrangement TODO: Currently only for LP version of convolutional layers. Extend also to normal convolution? To be used only with low precision (LP) version of caffe (caffe_lp/ ), beca...
11,262
38.658451
290
py
ADaPTION
ADaPTION-master/python/caffe/imagenet/cnn_to_NullHop.py
#!/usr/bin/env python """ Authors: federico.corradi@inilabs.com, diederikmoeys@live.com Converts caffe networks into jAER xml format this script requires command line arguments: model file -> network.prototxt weights file -> caffenet.model ...
31,660
49.335453
181
py
ADaPTION
ADaPTION-master/python/caffe/imagenet/convert_caffemodel_nullhop.py
import glob import os import numpy as np import matplotlib.pyplot as plt import caffe caffe_root = '../../../' caffe.set_mode_gpu() caffe.set_device(0) modelName = 'LP_VGG16' if modelName == 'resnets': model_def = '/users/hesham/trained_models/resNets/ResNet-50-deploy.prototxt' model_weights = '/users/hesham/...
7,417
41.632184
147
py
ADaPTION
ADaPTION-master/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
ADaPTION
ADaPTION-master/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
ADaPTION
ADaPTION-master/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
ADaPTION
ADaPTION-master/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
ADaPTION
ADaPTION-master/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
ADaPTION
ADaPTION-master/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...
9,656
26.910405
78
py
ADaPTION
ADaPTION-master/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,287
39.097561
77
py
ADaPTION
ADaPTION-master/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
ADaPTION
ADaPTION-master/python/caffe/quantization/convert_weights.py
''' This script converts weights, which are trained without rounding, to match the size of the data blobs of low precison rounded weights. In high precision each conv layer has two blob allocated for the weights and the biases However in low precision, since we are using dual copy roudning/pow2quantization, we basicall...
9,219
49.382514
137
py
ADaPTION
ADaPTION-master/python/caffe/quantization/__init__.py
0
0
0
py
ADaPTION
ADaPTION-master/python/caffe/quantization/qmf_check.py
''' This script loads an already trained CNN and prepares the Qm.f notation for each layer. Weights and activation are considered. This distribution is used by net_descriptor to build a new prototxt file to finetune the quantized weights and activations List of functions, for further details see below - forward_pa...
14,568
48.386441
136
py
ADaPTION
ADaPTION-master/python/caffe/quantization/net_descriptor.py
''' This script reads out a given prototxt file to extract the network layout Based on this network layout we create a new prototxt for either training or testing List of functions, for further details see below - get_model - extract - create Author: Moritz Milde Date: 02.11.2016 E-Mail: mmilde@ini.uzh.c...
42,894
58.825662
155
py
ADaPTION
ADaPTION-master/scripts/cpp_lint.py
#!/usr/bin/python2 # # 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 of...
187,448
37.49846
93
py
ADaPTION
ADaPTION-master/scripts/download_model_binary.py
#!/usr/bin/env python import os import sys import time import yaml import urllib import hashlib import argparse required_keys = ['caffemodel', 'caffemodel_url', 'sha1'] def reporthook(count, block_size, total_size): """ From http://blog.moleculea.com/2012/10/04/urlretrieve-progres-indicator/ """ glob...
2,507
31.571429
78
py
ADaPTION
ADaPTION-master/scripts/copy_notebook.py
#!/usr/bin/env python """ Takes as arguments: 1. the path to a JSON file (such as an IPython notebook). 2. the path to output file If 'metadata' dict in the JSON file contains 'include_in_docs': true, then copies the file to output file, appending the 'metadata' property as YAML front-matter, adding the field 'categor...
1,089
32.030303
87
py
ADaPTION
ADaPTION-master/frcnn/tools/compress_net.py
#!/usr/bin/env python # -------------------------------------------------------- # Fast R-CNN # Copyright (c) 2015 Microsoft # Licensed under The MIT License [see LICENSE for details] # Written by Ross Girshick # -------------------------------------------------------- """Compress a Fast R-CNN network using truncated...
3,918
30.103175
81
py
ADaPTION
ADaPTION-master/frcnn/tools/train_faster_rcnn_alt_opt.py
#!/usr/bin/env python # -------------------------------------------------------- # Faster R-CNN # Copyright (c) 2015 Microsoft # Licensed under The MIT License [see LICENSE for details] # Written by Ross Girshick # -------------------------------------------------------- """Train a Faster R-CNN network using alternat...
12,767
36.116279
80
py
ADaPTION
ADaPTION-master/frcnn/tools/reval.py
#!/usr/bin/env python # -------------------------------------------------------- # Fast R-CNN # Copyright (c) 2015 Microsoft # Licensed under The MIT License [see LICENSE for details] # Written by Ross Girshick # -------------------------------------------------------- """Reval = re-eval. Re-evaluate saved detections...
2,126
30.746269
76
py
ADaPTION
ADaPTION-master/frcnn/tools/test_net.py
#!/usr/bin/env python # -------------------------------------------------------- # Fast R-CNN # Copyright (c) 2015 Microsoft # Licensed under The MIT License [see LICENSE for details] # Written by Ross Girshick # -------------------------------------------------------- """Test a Fast R-CNN network on an image databas...
3,165
33.791209
77
py
ADaPTION
ADaPTION-master/frcnn/tools/_init_paths.py
# -------------------------------------------------------- # Fast R-CNN # Copyright (c) 2015 Microsoft # Licensed under The MIT License [see LICENSE for details] # Written by Ross Girshick # -------------------------------------------------------- """Set up paths for Fast R-CNN.""" import os.path as osp import sys ...
690
24.592593
68
py
ADaPTION
ADaPTION-master/frcnn/tools/demo.py
#!/usr/bin/env python # -------------------------------------------------------- # Faster R-CNN # Copyright (c) 2015 Microsoft # Licensed under The MIT License [see LICENSE for details] # Written by Ross Girshick # -------------------------------------------------------- """ Demo script showing detections in sample i...
5,067
31.075949
80
py