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 |
|---|---|---|---|---|---|---|
AlignShift | AlignShift-master/mmdet/models/backbones/resnext.py | import math
import torch.nn as nn
from mmdet.ops import DeformConv, ModulatedDeformConv
from ..registry import BACKBONES
from ..utils import build_conv_layer, build_norm_layer
from .resnet import Bottleneck as _Bottleneck
from .resnet import ResNet
class Bottleneck(_Bottleneck):
def __init__(self, inplanes, pl... | 8,336 | 33.882845 | 79 | py |
AlignShift | AlignShift-master/mmdet/models/mask_heads/grid_head.py | import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from mmcv.cnn import kaiming_init, normal_init
from ..builder import build_loss
from ..registry import HEADS
from ..utils import ConvModule
@HEADS.register_module
class GridHead(nn.Module):
def __init__(self,
... | 15,429 | 41.624309 | 79 | py |
AlignShift | AlignShift-master/mmdet/models/mask_heads/maskiou_head.py | import numpy as np
import torch
import torch.nn as nn
from mmcv.cnn import kaiming_init, normal_init
from torch.nn.modules.utils import _pair
from mmdet.core import force_fp32
from ..builder import build_loss
from ..registry import HEADS
@HEADS.register_module
class MaskIoUHead(nn.Module):
"""Mask IoU Head.
... | 7,453 | 38.026178 | 79 | py |
AlignShift | AlignShift-master/mmdet/models/mask_heads/fcn_mask_head.py | import mmcv
import numpy as np
import pycocotools.mask as mask_util
import torch
import torch.nn as nn
from torch.nn.modules.utils import _pair
from mmdet.core import auto_fp16, force_fp32, mask_target
from ..builder import build_loss
from ..registry import HEADS
from ..utils import ConvModule
@HEADS.register_module... | 7,271 | 37.887701 | 79 | py |
AlignShift | AlignShift-master/mmdet/models/mask_heads/fused_semantic_head.py | import torch.nn as nn
import torch.nn.functional as F
from mmcv.cnn import kaiming_init
from mmdet.core import auto_fp16, force_fp32
from ..registry import HEADS
from ..utils import ConvModule
@HEADS.register_module
class FusedSemanticHead(nn.Module):
r"""Multi-level fused semantic segmentation head.
in_1 -... | 3,554 | 32.224299 | 79 | py |
AlignShift | AlignShift-master/mmdet/datasets/custom.py | import os.path as osp
import mmcv
import numpy as np
from torch.utils.data import Dataset
from .pipelines import Compose
from .registry import DATASETS
@DATASETS.register_module
class CustomDataset(Dataset):
"""Custom dataset for detection.
Annotation format:
[
{
'filename': 'a.jpg'... | 5,047 | 32.653333 | 75 | py |
AlignShift | AlignShift-master/mmdet/datasets/dataset_wrappers.py | import numpy as np
from torch.utils.data.dataset import ConcatDataset as _ConcatDataset
from .registry import DATASETS
@DATASETS.register_module
class ConcatDataset(_ConcatDataset):
"""A wrapper of concatenated dataset.
Same as :obj:`torch.utils.data.dataset.ConcatDataset`, but
concat the group flag for... | 1,639 | 28.285714 | 78 | py |
AlignShift | AlignShift-master/mmdet/datasets/loader/sampler.py | from __future__ import division
import math
import numpy as np
import torch
from mmcv.runner import get_dist_info
from torch.utils.data import DistributedSampler as _DistributedSampler
from torch.utils.data import Sampler
class DistributedSampler(_DistributedSampler):
def __init__(self, dataset, num_replicas=No... | 5,860 | 34.521212 | 78 | py |
AlignShift | AlignShift-master/mmdet/datasets/loader/build_loader.py | import platform
from functools import partial
from mmcv.parallel import collate
from mmcv.runner import get_dist_info
from torch.utils.data import DataLoader
from .sampler import DistributedGroupSampler, DistributedSampler, GroupSampler
if platform.system() != 'Windows':
# https://github.com/pytorch/pytorch/issu... | 1,552 | 30.693878 | 78 | py |
AlignShift | AlignShift-master/mmdet/datasets/pipelines/formating.py | from collections.abc import Sequence
import mmcv
import numpy as np
import torch
from mmcv.parallel import DataContainer as DC
from ..registry import PIPELINES
def to_tensor(data):
"""Convert objects of various python types to :obj:`torch.Tensor`.
Supported types are: :class:`numpy.ndarray`, :class:`torch.... | 5,994 | 31.058824 | 79 | py |
AlignShift | AlignShift-master/mmdet/utils/flops_counter.py | # Modified from flops-counter.pytorch by Vladislav Sovrasov
# original repo: https://github.com/sovrasov/flops-counter.pytorch
# MIT License
# Copyright (c) 2018 Vladislav Sovrasov
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (th... | 14,351 | 32.069124 | 79 | py |
AlignShift | AlignShift-master/mmdet/ops/context_block.py | import torch
from mmcv.cnn import constant_init, kaiming_init
from torch import nn
def last_zero_init(m):
if isinstance(m, nn.Sequential):
constant_init(m[-1], val=0)
else:
constant_init(m, val=0)
class ContextBlock(nn.Module):
def __init__(self,
inplanes,
... | 3,766 | 34.87619 | 76 | py |
AlignShift | AlignShift-master/mmdet/ops/dcn/deform_pool.py | import torch
import torch.nn as nn
from torch.autograd import Function
from torch.autograd.function import once_differentiable
from torch.nn.modules.utils import _pair
from . import deform_pool_cuda
class DeformRoIPoolingFunction(Function):
@staticmethod
def forward(ctx,
data,
... | 10,212 | 39.367589 | 79 | py |
AlignShift | AlignShift-master/mmdet/ops/dcn/deform_conv.py | import math
import torch
import torch.nn as nn
from torch.autograd import Function
from torch.autograd.function import once_differentiable
from torch.nn.modules.utils import _pair
from . import deform_conv_cuda
class DeformConvFunction(Function):
@staticmethod
def forward(ctx,
input,
... | 12,468 | 35.890533 | 79 | py |
AlignShift | AlignShift-master/mmdet/ops/masked_conv/masked_conv.py | import math
import torch
import torch.nn as nn
from torch.autograd import Function
from torch.autograd.function import once_differentiable
from torch.nn.modules.utils import _pair
from . import masked_conv2d_cuda
class MaskedConv2dFunction(Function):
@staticmethod
def forward(ctx, features, mask, weight, b... | 3,375 | 36.511111 | 79 | py |
AlignShift | AlignShift-master/mmdet/ops/sigmoid_focal_loss/sigmoid_focal_loss.py | import torch.nn as nn
from torch.autograd import Function
from torch.autograd.function import once_differentiable
from . import sigmoid_focal_loss_cuda
class SigmoidFocalLossFunction(Function):
@staticmethod
def forward(ctx, input, target, gamma=2.0, alpha=0.25):
ctx.save_for_backward(input, target)... | 1,637 | 28.781818 | 77 | py |
AlignShift | AlignShift-master/mmdet/ops/roi_align/roi_align.py | import torch.nn as nn
from torch.autograd import Function
from torch.autograd.function import once_differentiable
from torch.nn.modules.utils import _pair
from . import roi_align_cuda
class RoIAlignFunction(Function):
@staticmethod
def forward(ctx, features, rois, out_size, spatial_scale, sample_num=0):
... | 3,068 | 33.875 | 79 | py |
AlignShift | AlignShift-master/mmdet/ops/roi_align/gradcheck.py | import os.path as osp
import sys
import numpy as np
import torch
from torch.autograd import gradcheck
sys.path.append(osp.abspath(osp.join(__file__, '../../')))
from roi_align import RoIAlign # noqa: E402, isort:skip
feat_size = 15
spatial_scale = 1.0 / 8
img_size = feat_size / spatial_scale
num_imgs = 2
num_rois =... | 879 | 27.387097 | 76 | py |
AlignShift | AlignShift-master/mmdet/ops/roi_pool/roi_pool.py | import torch
import torch.nn as nn
from torch.autograd import Function
from torch.autograd.function import once_differentiable
from torch.nn.modules.utils import _pair
from . import roi_pool_cuda
class RoIPoolFunction(Function):
@staticmethod
def forward(ctx, features, rois, out_size, spatial_scale):
... | 2,544 | 32.486842 | 78 | py |
AlignShift | AlignShift-master/mmdet/ops/roi_pool/gradcheck.py | import os.path as osp
import sys
import torch
from torch.autograd import gradcheck
sys.path.append(osp.abspath(osp.join(__file__, '../../')))
from roi_pool import RoIPool # noqa: E402, isort:skip
feat = torch.randn(4, 16, 15, 15, requires_grad=True).cuda()
rois = torch.Tensor([[0, 0, 0, 50, 50], [0, 10, 30, 43, 55]... | 513 | 29.235294 | 66 | py |
AlignShift | AlignShift-master/mmdet/ops/nms/nms_wrapper.py | import numpy as np
import torch
from . import nms_cpu, nms_cuda
from .soft_nms_cpu import soft_nms_cpu
def nms(dets, iou_thr, device_id=None):
"""Dispatch to either CPU or GPU NMS implementations.
The input can be either a torch tensor or numpy array. GPU NMS will be used
if the input is a gpu tensor or... | 3,663 | 34.572816 | 79 | 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/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/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/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/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/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 |
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/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/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/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/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/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/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 |
ADaPTION | ADaPTION-master/frcnn/tools/lp_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,772 | 36.130814 | 80 | py |
ADaPTION | ADaPTION-master/frcnn/tools/train_svms.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
# --------------------------------------------------------
"""
Train post-hoc SVMs using the algorithm and ... | 13,480 | 37.081921 | 80 | py |
ADaPTION | ADaPTION-master/frcnn/tools/rpn_generate.py | #!/usr/bin/env python
# --------------------------------------------------------
# Fast/er/ R-CNN
# Copyright (c) 2015 Microsoft
# Licensed under The MIT License [see LICENSE for details]
# Written by Ross Girshick
# --------------------------------------------------------
"""Generate RPN proposals."""
import _init_... | 2,994 | 31.554348 | 78 | py |
ADaPTION | ADaPTION-master/frcnn/tools/train_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
# --------------------------------------------------------
"""Train a Fast R-CNN network on a region of int... | 3,747 | 32.168142 | 78 | py |
ADaPTION | ADaPTION-master/frcnn/lib/roi_data_layer/layer.py | # --------------------------------------------------------
# Fast R-CNN
# Copyright (c) 2015 Microsoft
# Licensed under The MIT License [see LICENSE for details]
# Written by Ross Girshick
# --------------------------------------------------------
"""The data layer used during training to train a Fast R-CNN network.
... | 7,449 | 36.817259 | 81 | py |
ADaPTION | ADaPTION-master/frcnn/lib/roi_data_layer/minibatch.py | # --------------------------------------------------------
# Fast R-CNN
# Copyright (c) 2015 Microsoft
# Licensed under The MIT License [see LICENSE for details]
# Written by Ross Girshick
# --------------------------------------------------------
"""Compute minibatch blobs for training a Fast R-CNN network."""
impor... | 8,169 | 39.85 | 81 | py |
ADaPTION | ADaPTION-master/frcnn/lib/fast_rcnn/test.py | # --------------------------------------------------------
# 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 imdb (image database)."""
from fast... | 11,126 | 35.601974 | 83 | py |
ADaPTION | ADaPTION-master/frcnn/lib/fast_rcnn/config.py | # --------------------------------------------------------
# Fast R-CNN
# Copyright (c) 2015 Microsoft
# Licensed under The MIT License [see LICENSE for details]
# Written by Ross Girshick
# --------------------------------------------------------
"""Fast R-CNN config system.
This file specifies default config option... | 9,213 | 31.216783 | 91 | py |
ADaPTION | ADaPTION-master/frcnn/lib/fast_rcnn/train.py | # --------------------------------------------------------
# Fast R-CNN
# Copyright (c) 2015 Microsoft
# Licensed under The MIT License [see LICENSE for details]
# Written by Ross Girshick
# --------------------------------------------------------
"""Train a Fast R-CNN network."""
import caffe
from fast_rcnn.config i... | 6,076 | 36.282209 | 79 | py |
ADaPTION | ADaPTION-master/frcnn/lib/rpn/proposal_layer.py | # --------------------------------------------------------
# Faster R-CNN
# Copyright (c) 2015 Microsoft
# Licensed under The MIT License [see LICENSE for details]
# Written by Ross Girshick and Sean Bell
# --------------------------------------------------------
import caffe
import numpy as np
import yaml
from fast_r... | 7,171 | 37.352941 | 89 | py |
ADaPTION | ADaPTION-master/frcnn/lib/rpn/proposal_target_layer.py | # --------------------------------------------------------
# Faster R-CNN
# Copyright (c) 2015 Microsoft
# Licensed under The MIT License [see LICENSE for details]
# Written by Ross Girshick and Sean Bell
# --------------------------------------------------------
import caffe
import yaml
import numpy as np
import nump... | 7,494 | 37.634021 | 85 | py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.