code stringlengths 17 6.64M |
|---|
class BoxAnnotatorOHEMOperator(mx.operator.CustomOp):
def __init__(self, num_classes, num_reg_classes, rm_last, roi_per_img):
super(BoxAnnotatorOHEMOperator, self).__init__()
self._num_classes = num_classes
self._num_reg_classes = num_reg_classes
self._roi_per_img = roi_per_img
... |
@mx.operator.register('BoxAnnotatorOHEM')
class BoxAnnotatorOHEMProp(mx.operator.CustomOpProp):
def __init__(self, num_classes, num_reg_classes, rm_last, roi_per_img):
super(BoxAnnotatorOHEMProp, self).__init__(need_top_grad=False)
self._num_classes = int(num_classes)
self._num_reg_classe... |
class resnet_v1_101_fpn_dcn_rcnn(Symbol):
def __init__(self):
'\n Use __init__ to define parameter network needs\n '
self.shared_param_list = ['offset_p2', 'offset_p3', 'offset_p4', 'offset_p5', 'rpn_conv', 'rpn_cls_score', 'rpn_bbox_pred']
self.shared_param_dict = {}
... |
class resnet_v1_101_fpn_dcn_rcnn_oneshot_v3(Symbol):
def __init__(self):
'\n Use __init__ to define parameter network needs\n '
self.shared_param_list = ['offset_p2', 'offset_p3', 'offset_p4', 'offset_p5', 'rpn_conv', 'rpn_cls_score', 'rpn_bbox_pred']
self.shared_param_dict ... |
class resnet_v1_101_fpn_dcn_rcnn_rep_noemb(Symbol):
def __init__(self):
'\n Use __init__ to define parameter network needs\n '
self.shared_param_list = ['offset_p2', 'offset_p3', 'offset_p4', 'offset_p5', 'rpn_conv', 'rpn_cls_score', 'rpn_bbox_pred']
self.shared_param_dict =... |
class resnet_v1_101_fpn_rcnn(Symbol):
def __init__(self):
'\n Use __init__ to define parameter network needs\n '
self.shared_param_list = ['rpn_conv', 'rpn_cls_score', 'rpn_bbox_pred']
self.shared_param_dict = {}
for name in self.shared_param_list:
self.s... |
def customize_compiler_for_nvcc(self):
"inject deep into distutils to customize how the dispatch\n to gcc/nvcc works.\n If you subclass UnixCCompiler, it's not trivial to get your subclass\n injected in, and still have the right customizations (i.e.\n distutils.sysconfig.customize_compiler) run on it.... |
class custom_build_ext(build_ext):
def build_extensions(self):
customize_compiler_for_nvcc(self.compiler)
build_ext.build_extensions(self)
|
def find_in_path(name, path):
'Find a file in a search path'
for dir in path.split(os.pathsep):
binpath = pjoin(dir, name)
if os.path.exists(binpath):
return os.path.abspath(binpath)
return None
|
def locate_cuda():
"Locate the CUDA environment on the system\n Returns a dict with keys 'home', 'nvcc', 'include', and 'lib64'\n and values giving the absolute path to each directory.\n Starts by looking for the CUDAHOME env variable. If not found, everything\n is based on finding 'nvcc' in the PATH.... |
def customize_compiler_for_nvcc(self):
"inject deep into distutils to customize how the dispatch\n to gcc/nvcc works.\n If you subclass UnixCCompiler, it's not trivial to get your subclass\n injected in, and still have the right customizations (i.e.\n distutils.sysconfig.customize_compiler) run on it.... |
class custom_build_ext(build_ext):
def build_extensions(self):
customize_compiler_for_nvcc(self.compiler)
build_ext.build_extensions(self)
|
def find_in_path(name, path):
'Find a file in a search path'
for dir in path.split(os.pathsep):
binpath = pjoin(dir, name)
if os.path.exists(binpath):
return os.path.abspath(binpath)
return None
|
def locate_cuda():
"Locate the CUDA environment on the system\n\n Returns a dict with keys 'home', 'nvcc', 'include', and 'lib64'\n and values giving the absolute path to each directory.\n\n Starts by looking for the CUDAHOME env variable. If not found, everything\n is based on finding 'nvcc' in the P... |
def customize_compiler_for_nvcc(self):
"inject deep into distutils to customize how the dispatch\n to gcc/nvcc works.\n\n If you subclass UnixCCompiler, it's not trivial to get your subclass\n injected in, and still have the right customizations (i.e.\n distutils.sysconfig.customize_compiler) run on i... |
class custom_build_ext(build_ext):
def build_extensions(self):
customize_compiler_for_nvcc(self.compiler)
build_ext.build_extensions(self)
|
class CUDA_build_ext(build_ext):
'\n Custom build_ext command that compiles CUDA files.\n Note that all extension source files will be processed with this compiler.\n '
def build_extensions(self):
self.compiler.src_extensions.append('.cu')
self.compiler.set_executable('compiler_so', ... |
def get_segmentation_test_batch(segdb, config):
"\n return a dict of train batch\n :param segdb: ['image', 'flipped']\n :param config: the config setting\n :return: data, label, im_info\n "
(imgs, seg_cls_gts, segdb) = get_segmentation_image(segdb, config)
im_array = imgs
im_info = [np.... |
def get_segmentation_train_batch(segdb, config):
"\n return a dict of train batch\n :param segdb: ['image', 'flipped']\n :param config: the config setting\n :return: data, label, im_info\n "
assert (len(segdb) == 1), 'Single batch only'
(imgs, seg_cls_gts, segdb) = get_segmentation_image(se... |
def file_lines_to_list(path):
with open(path) as f:
content = f.readlines()
content = [x.strip() for x in content]
return content
|
class Pred():
def __init__(self, id, conf, left, top, right, bottom):
self.id = id
self.conf = conf
self.left = left
self.top = top
self.right = right
self.bottom = bottom
def calc_pred_intersection(self, pred):
if (not (self.id == pred.id)):
... |
def plot_preds(img, preds, clr=(255, 0, 255)):
if isinstance(img, str):
img = cv2.imread(img)
for pred in preds:
cv2.rectangle(img, (pred.left, pred.top), (pred.right, pred.bottom), clr)
cv2.putText(img, pred.id, (pred.left, pred.top), cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 255, 255), 2, c... |
def read_predictions(txt_file):
lines_list = file_lines_to_list(txt_file)
prediction = []
for line in lines_list:
(id, conf, left, top, right, bottom) = line.split(';')
pred = Pred(id, float(conf), int(left), int(top), int(right), int(bottom))
prediction.append(pred)
return pre... |
class ObjDetStats():
def __init__(self, gt_roidb_fname, cat_ords, logger):
with open(gt_roidb_fname, 'rb') as fid:
self.roidb = cPickle.load(fid)
self.roidb_ni = {}
for entry in self.roidb:
image_path = entry['image']
(im_path, im_name) = os.path.split(... |
class PrefetchingIter(mx.io.DataIter):
'Base class for prefetching iterators. Takes one or more DataIters (\n or any class with "reset" and "next" methods) and combine them with\n prefetching. For example:\n\n Parameters\n ----------\n iters : DataIter or list of DataIter\n one or more DataI... |
def combine_model(prefix1, epoch1, prefix2, epoch2, prefix_out, epoch_out):
(args1, auxs1) = load_checkpoint(prefix1, epoch1)
(args2, auxs2) = load_checkpoint(prefix2, epoch2)
arg_names = (args1.keys() + args2.keys())
aux_names = (auxs1.keys() + auxs2.keys())
args = dict()
for arg in arg_names... |
@mx.init.register
class MyConstant(mx.init.Initializer):
def __init__(self, value):
super(MyConstant, self).__init__(value=value)
self.value = value
def _init_weight(self, _, arr):
arr[:] = mx.nd.array(self.value)
|
def create_logger(root_output_path, cfg, image_set):
if (not os.path.exists(root_output_path)):
os.makedirs(root_output_path)
assert os.path.exists(root_output_path), '{} does not exist'.format(root_output_path)
cfg_name = os.path.basename(cfg).split('.')[0]
config_output_path = os.path.join(r... |
class UnknownImageFormat(Exception):
pass
|
class Image(collections.namedtuple('Image', image_fields)):
def to_str_row(self):
return ('%d\t%d\t%d\t%s\t%s' % (self.width, self.height, self.file_size, self.type, self.path.replace('\t', '\\t')))
def to_str_row_verbose(self):
return ('%d\t%d\t%d\t%s\t%s\t##%s' % (self.width, self.height, ... |
def get_image_size(file_path):
'\n Return (width, height) for a given img file content - no external\n dependencies except the os and struct builtin modules\n '
img = get_image_metadata(file_path)
return (img.width, img.height)
|
def get_image_size_from_bytesio(input, size):
'\n Return (width, height) for a given img file content - no external\n dependencies except the os and struct builtin modules\n\n Args:\n input (io.IOBase): io object support read & seek\n size (int): size of buffer in byte\n '
img = get_... |
def get_image_metadata(file_path):
'\n Return an `Image` object for a given img file content - no external\n dependencies except the os and struct builtin modules\n\n Args:\n file_path (str): path to an image file\n\n Returns:\n Image: (path, type, file_size, width, height)\n '
si... |
def get_image_metadata_from_bytesio(input, size, file_path=None):
'\n Return an `Image` object for a given img file content - no external\n dependencies except the os and struct builtin modules\n\n Args:\n input (io.IOBase): io object support read & seek\n size (int): size of buffer in byte... |
class Test_get_image_size(unittest.TestCase):
data = [{'path': 'lookmanodeps.png', 'width': 251, 'height': 208, 'file_size': 22228, 'type': 'PNG'}]
def setUp(self):
pass
def test_get_image_size_from_bytesio(self):
img = self.data[0]
p = img['path']
with io.open(p, 'rb') a... |
def main(argv=None):
'\n Print image metadata fields for the given file path.\n\n Keyword Arguments:\n argv (list): commandline arguments (e.g. sys.argv[1:])\n Returns:\n int: zero for OK\n '
import logging
import optparse
import sys
prs = optparse.OptionParser(usage='%pr... |
def load_checkpoint(prefix, epoch):
"\n Load model checkpoint from file.\n :param prefix: Prefix of model name.\n :param epoch: Epoch number of model we would like to load.\n :return: (arg_params, aux_params)\n arg_params : dict of str to NDArray\n Model parameter, dict of name to NDArray of... |
def convert_context(params, ctx):
'\n :param params: dict of str to NDArray\n :param ctx: the context to convert to\n :return: dict of str of NDArray with context ctx\n '
new_params = dict()
for (k, v) in params.items():
new_params[k] = v.as_in_context(ctx)
return new_params
|
def load_param(prefix, epoch, convert=False, ctx=None, process=False):
'\n wrapper for load checkpoint\n :param prefix: Prefix of model name.\n :param epoch: Epoch number of model we would like to load.\n :param convert: reference model should be converted to GPU NDArray first\n :param ctx: if conv... |
class WarmupMultiFactorScheduler(LRScheduler):
'Reduce learning rate in factor at steps specified in a list\n\n Assume the weight has been updated by n times, then the learning rate will\n be\n\n base_lr * factor^(sum((step/n)<=1)) # step is an array\n\n Parameters\n ----------\n step: list of i... |
def save_checkpoint(prefix, epoch, arg_params, aux_params):
"Checkpoint the model data into file.\n :param prefix: Prefix of model name.\n :param epoch: The epoch number of the model.\n :param arg_params: dict of str to NDArray\n Model parameter, dict of name to NDArray of net's weights.\n :par... |
class Symbol():
def __init__(self):
self.arg_shape_dict = None
self.out_shape_dict = None
self.aux_shape_dict = None
self.sym = None
@property
def symbol(self):
return self.sym
def get_symbol(self, cfg, is_train=True):
'\n return a generated sy... |
def tic():
import time
global startTime_for_tictoc
startTime_for_tictoc = time.time()
return startTime_for_tictoc
|
def toc():
if ('startTime_for_tictoc' in globals()):
endTime = time.time()
return (endTime - startTime_for_tictoc)
else:
return None
|
def get_dets_class_names(dets_n):
for det in dets_n:
class_names = []
for prd in det[3]:
if (prd in prd2ename.keys()):
class_names += [prd2ename[prd]]
else:
class_names += [prd]
det += [class_names]
return dets_n
|
def print_typical_tray_multiview():
imgname_left = os.path.join(data_root, '15849_left.jpg')
imgname_top = os.path.join(data_root, '15849_top.jpg')
imgname_right = os.path.join(data_root, '15849_right.jpg')
img_left = mpimg.imread(imgname_left)
img_top = mpimg.imread(imgname_top)
img_right = m... |
def display_few_shot_examples():
image_set = ['5cadb37d4b967f67d3047964.jpg', '12686073-1-white.jpg', 'lacoste-logo-sweatshirt-white-p12654-72879_image.jpg']
fig = plt.figure(2)
ff = 2
fig.set_size_inches(((ff * 8.5), ((3 * ff) * 11)), forward=False)
for (cnt, img_basename) in enumerate(image_set)... |
def test_on_query_image(fs_serv, test_img_fname, det_engines):
img = cv2.imread(test_img_fname, (cv2.IMREAD_COLOR | cv2.IMREAD_IGNORE_ORIENTATION))
score_thresh = 0.1
dets_n = fs_serv.detect_on_image(img, score_thresh=score_thresh, det_engines=det_engines)
dets_n = get_dets_class_names(dets_n)
tes... |
def get_box_proposal(fs_serv, img_path):
from show_boxes import show_detsB_boxes
q_dets_p = fs_serv.get_box_proposal(img_path)
image_basename = os.path.basename(img_path)
save_file_path = os.path.join(disp_folder, 'box_prop_{0}'.format(image_basename))
img = cv2.cvtColor(cv2.imread(img_path, (cv2.... |
def disp_dets2(img, dets, save_file_path):
import matplotlib.pyplot as plt
fig = plt.figure(1)
fig.set_size_inches(((1.4 * 8.5), (1.4 * 11)), forward=False)
plt.axis('off')
img_d = cv2.cvtColor(copy.deepcopy(img), cv2.COLOR_BGR2RGB)
w = 12
for det in dets:
bbox = det[0]
sco... |
def test_on_query_image(fs_serv, test_img_fname, score_thresh=0.1, det_engines=1, figure_factor=2.2, FontScale=2.3):
img = cv2.imread(test_img_fname, (cv2.IMREAD_COLOR | cv2.IMREAD_IGNORE_ORIENTATION))
dets_n = fs_serv.detect_on_image(img, score_thresh=score_thresh, det_engines=det_engines)
test_img_basen... |
def display_RedHat_examples():
image_set = ['logo1.jpg', 'logo2.jpg', 'logo3.jpg']
fig = plt.figure(2)
ff = 2
fig.set_size_inches(((ff * 8.5), ((3 * ff) * 11)), forward=False)
enrollment_root = '../data/Logo/logo_usecase_data/RedHat/RedHat_enrollment'
for (cnt, img_basename) in enumerate(image... |
def display_lacoste_examples():
image_set = ['5cadb37d4b967f67d3047964.jpg', 'lacoste-logo-sweatshirt-white-p12654-72879_image.jpg', '12686073-1-white.jpg']
fig = plt.figure(2)
ff = 2
fig.set_size_inches(((ff * 8.5), ((3 * ff) * 11)), forward=False)
enrollment_root = '../data/Logo/logo_usecase_dat... |
def display_few_shot_examples():
data_root = '/dccstor/jsdata1/dev/RepMet/notebooks/food_usecase_data'
image_set = ['PRDS990000000000000025_0_192_501_589_885_top.jpg', 'PRDS990000000000000024_0_119_137_523_447_top.jpg', 'PRDS990000000000000023_0_118_208_470_612_top.jpg', 'PRDS990000000000000021_0_571_234_923_... |
def print_typical_tray_multiview():
imgname_left = os.path.join(data_root, '1007_10000000006530_left.jpg')
imgname_top = os.path.join(data_root, '1007_10000000006530_top.jpg')
imgname_right = os.path.join(data_root, '1007_10000000006530_right.jpg')
img_left = mpimg.imread(imgname_left)
img_top = m... |
def disp_dets(img, dets, save_file_path):
import matplotlib.pyplot as plt
fig = plt.figure(1)
ff = 2
fig.set_size_inches(((ff * 8.5), (ff * 11)), forward=False)
plt.axis('off')
img_d = cv2.cvtColor(copy.deepcopy(img), cv2.COLOR_BGR2RGB)
for det in dets:
bbox = det[0]
scores... |
def test_on_query_image(fs_serv, test_img_fname, det_engines):
prd2ename_fname = '/dccstor/jsdata1/dev/RepMet/data/JES_pilot/all_GT.csv_converted_Feb24_prd2ename.csv'
prd2ename_data = np.load(prd2ename_fname)
prd2ename = prd2ename_data['prd2ename']
img = cv2.imread(test_img_fname, (cv2.IMREAD_COLOR | ... |
def get_box_proposal(fs_serv, img_path):
from show_boxes import show_detsB_boxes
output_folder = '../notebooks/food_usecase_data'
q_dets_p = fs_serv.get_box_proposal(img_path)
image_basename = os.path.basename(img_path)
save_file_path = os.path.join(output_folder, 'box_prop_{0}'.format(image_basen... |
def display_few_shot_examples():
data_root = '/opt/DNN/dataset/retail/retail_test'
image_set = ['0de3ec888566edc2.jpg', '2e90529bcb43f44c.jpg', '15a8f82801fe4911.jpg', '34caf4cf9ae0ae92.jpg']
nrows = 1
ncols = np.ceil((len(image_set) / nrows))
print('nrows={0},ncols={1}'.format(nrows, ncols))
... |
def print_typical_tray_multiview():
data_root = '/opt/DNN/dataset/retail/retail_test'
imgname_left = os.path.join(data_root, '0de3ec888566edc2.jpg')
imgname_top = os.path.join(data_root, '2e90529bcb43f44c.jpg')
imgname_right = os.path.join(data_root, '15a8f82801fe4911.jpg')
img_left = mpimg.imread... |
def oid2coco():
img_dir = '/opt/DNN/dataset/openimage/openimage_train'
boxes_csv = '/opt/DNN/dataset/openimage/retail.csv'
json_file = '/opt/DNN/dataset/openimage/annotations/instances_openimage_train.json'
classes_csv = '/opt/DNN/linkdata/eval_dataset/open_images/metadata/class-descriptions-boxable.c... |
def show_detsB_boxes(im, dets_B, scale=1.0, save_file_path='temp.png'):
fig = plt.figure(1)
ff = 1.0
fig.set_size_inches(((ff * 8.5), (ff * 11)), forward=False)
plt.cla()
plt.axis('off')
plt.imshow(im)
for det in dets_B:
det_row = det[0]
cat_name = det[2]
bbox = (de... |
def display_few_shot_test(benchmark, query_image):
import shutil
from FSD_engine import FSD_RepMet as DetectionEngine
from config.bench_config import bcfg, update_bench_config
import cv2
update_bench_config('../experiments/bench_configs/openimage_3_5_10_1.yaml')
(q_dets_B, q_dets_multi_B) = be... |
def Conv(incoming, num_filters, filter_size=3, stride=(1, 1), pad='same', W=lasagne.init.HeNormal(), b=None, nonlinearity=lasagne.nonlinearities.rectify, **kwargs):
'\n Overrides the default parameters for ConvLayer\n '
ensure_set_name('conv', kwargs)
return ConvLayer(incoming, num_filters, filter_s... |
class ConvPrelu(Layer):
def __init__(self, incoming, num_filters, filter_size=3, stride=(1, 1), pad='same', W=lasagne.init.HeNormal(), b=None, **kwargs):
ensure_set_name('conv_prelu', kwargs)
super(ConvPrelu, self).__init__(incoming, **kwargs)
self.conv = Conv(incoming, num_filters, filte... |
class ConvAggr(Layer):
def __init__(self, incoming, num_channels, filter_size=3, stride=(1, 1), pad='same', W=lasagne.init.HeNormal(), b=None, **kwargs):
ensure_set_name('conv_aggr', kwargs)
super(ConvAggr, self).__init__(incoming, **kwargs)
self.conv = Conv(incoming, num_channels, filter... |
def Conv3D(incoming, num_filters, filter_size=3, stride=(1, 1, 1), pad='same', W=lasagne.init.HeNormal(), b=lasagne.init.Constant(), nonlinearity=lasagne.nonlinearities.rectify, **kwargs):
'\n Overrides the default parameters for Conv3DLayer\n '
ensure_set_name('conv3d', kwargs)
return Conv3DLayer(i... |
class Conv3DPrelu(Layer):
def __init__(self, incoming, num_filters, filter_size=3, stride=(1, 1, 1), pad='same', W=lasagne.init.HeNormal(), b=None, **kwargs):
ensure_set_name('conv3d_prelu', kwargs)
super(Conv3DPrelu, self).__init__(incoming, **kwargs)
self.conv = Conv3D(incoming, num_fil... |
class Conv3DAggr(Layer):
def __init__(self, incoming, num_channels, filter_size=3, stride=(1, 1, 1), pad='same', W=lasagne.init.HeNormal(), b=None, **kwargs):
ensure_set_name('conv3d_aggr', kwargs)
super(Conv3DAggr, self).__init__(incoming, **kwargs)
self.conv = Conv3D(incoming, num_chann... |
class DataConsistencyLayer(MergeLayer):
'\n Data consistency layer\n '
def __init__(self, incomings, inv_noise_level=None, **kwargs):
super(DataConsistencyLayer, self).__init__(incomings, **kwargs)
self.inv_noise_level = inv_noise_level
def get_output_for(self, inputs, **kwargs):
... |
class DataConsistencyWithMaskLayer(MergeLayer):
'\n Data consistency layer\n '
def __init__(self, incomings, inv_noise_level=None, **kwargs):
super(DataConsistencyWithMaskLayer, self).__init__(incomings, **kwargs)
self.inv_noise_level = inv_noise_level
def get_output_for(self, inpu... |
class DCLayer(MergeLayer):
'\n Data consistency layer\n '
def __init__(self, incomings, data_shape, inv_noise_level=None, **kwargs):
if ('name' not in kwargs):
kwargs['name'] = 'dc'
super(DCLayer, self).__init__(incomings, **kwargs)
self.inv_noise_level = inv_noise_l... |
def ensure_set_name(default_name, kwargs):
"Ensure that the parameters contain names. Be careful, kwargs need to be\n passed as a dictionary here\n\n Parameters\n ----------\n default_name: string\n default name to set if neither name or pr is present, or if name is not\n present but pr ... |
def get_dc_input_layers(shape):
'\n Creates input layer for the CNN. Works for 2D and 3D input.\n\n Returns\n -------\n net: Ordered Dictionary\n net config with 3 entries: input, kspace_input, mask.\n '
if (len(shape) > 4):
input_var = tensor5('input_var')
kspace_input_va... |
def roll_and_sum(prior_result, orig):
res = (prior_result + orig)
res = T.roll(res, 1, axis=(- 1))
return res
|
class KspaceFillNeighbourLayer(MergeLayer):
'\n k-space fill layer - The input data is assumed to be in k-space grid.\n\n The input data is assumed to be in k-space grid.\n This layer should be invoked from AverageInKspaceLayer\n '
def __init__(self, incomings, frame_dist=range(5), divide_by_n=Fa... |
class KspaceFillNeighbourLayer_Clipped(MergeLayer):
'\n k-space fill layer with clipping at the edge.\n\n The input data is assumed to be in k-space grid.\n This layer should be invoked from AverageInKspaceLayer\n '
def __init__(self, incomings, nt, frame_dist=range(5), divide_by_n=False, **kwarg... |
class AverageInKspaceLayer(MergeLayer):
'\n Average-in-k-space layer\n\n First transforms the representation in Fourier domain,\n then performs averaging along temporal axis, then transforms back to image\n domain. Works only for 5D tensor (see parameter descriptions).\n\n\n Parameters\n -------... |
class PoolNDLayer(Layer):
"\n ND pooling layer\n\n Performs ND mean or max-pooling over the trailing axes\n of a ND input tensor.\n\n Parameters\n ----------\n incoming : a :class:`Layer` instance or tuple\n The layer feeding into this layer, or the expected input shape.\n\n pool_size ... |
class Upscale3DLayer(Layer):
'\n 3D upscaling layer\n Performs 3D upscaling over the two trailing axes of a 4D input tensor.\n Parameters\n ----------\n incoming : a :class:`Layer` instance or tuple\n The layer feeding into this layer, or the expected input shape.\n scale_factor : integer... |
class IdLayer(Layer):
def get_output_for(self, input, **kwargs):
return input
|
class SumLayer(Layer):
def get_output_for(self, input, **kwargs):
return input.sum(axis=(- 1))
def get_output_shape_for(self, input_shape):
return input_shape[:(- 1)]
|
class SHLULayer(Layer):
def get_output_for(self, input, **kwargs):
return (T.sgn(input) * T.maximum((input - 1), 0))
|
class ResidualLayer(lasagne.layers.ElemwiseSumLayer):
'\n Residual Layer, which just wraps around ElemwiseSumLayer\n '
def __init__(self, incomings, **kwargs):
ensure_set_name('res', kwargs)
super(ResidualLayer, self).__init__(incomings, **kwargs)
input_names = []
for l ... |
def cascade_resnet(pr, net, input_layer, n=5, nf=64, b=lasagne.init.Constant, **kwargs):
shape = lasagne.layers.get_output_shape(input_layer)
n_channel = shape[1]
net[(pr + 'conv1')] = l.Conv(input_layer, nf, 3, b=b(), name=(pr + 'conv1'))
for i in xrange(2, n):
net[(pr + ('conv%d' % i))] = l.... |
def cascade_resnet_3d_avg(pr, net, input_layer, n=5, nf=64, b=lasagne.init.Constant, frame_dist=range(5), **kwargs):
shape = lasagne.layers.get_output_shape(input_layer)
n_channel = shape[1]
divide_by_n = (kwargs['cascade_i'] != 0)
k = (3, 3, 3)
net[(pr + 'kavg')] = l.AverageInKspaceLayer([input_l... |
def build_cascade_cnn_from_list(shape, net_meta, lmda=None):
'\n Create iterative network with more flexibility\n\n net_meta: [(model1, cascade1_n),(model2, cascade2_n),....(modelm, cascadem_n),]\n '
if (not net_meta):
raise
net = OrderedDict()
(input_layer, kspace_input_layer, mask_l... |
def build_d2_c2(shape):
def cascade_d2(pr, net, input_layer, **kwargs):
return cascade_resnet(pr, net, input_layer, n=2)
return build_cascade_cnn_from_list(shape, [(cascade_d2, 2)])
|
def build_d5_c5(shape):
return build_cascade_cnn_from_list(shape, [(cascade_resnet, 5)])
|
def build_d2_c2_s(shape):
def cascade_d2(pr, net, input_layer, **kwargs):
return cascade_resnet_3d_avg(pr, net, input_layer, n=2, nf=16, frame_dist=range(2), **kwargs)
return build_cascade_cnn_from_list(shape, [(cascade_d2, 2)])
|
def build_d5_c10_s(shape):
return build_cascade_cnn_from_list(shape, [(cascade_resnet_3d_avg, 10)])
|
class FFTOp(gof.Op):
__props__ = ()
def output_type(self, inp):
return T.TensorType(inp.dtype, broadcastable=([False] * inp.type.ndim))
def make_node(self, a, s=None):
a = T.as_tensor_variable(a)
if (a.ndim < 3):
raise TypeError((('%s: input must have dimension >= 3, ... |
class IFFTOp(gof.Op):
__props__ = ()
def output_type(self, inp):
return T.TensorType(inp.dtype, broadcastable=([False] * inp.type.ndim))
def make_node(self, a, s=None):
a = T.as_tensor_variable(a)
if (a.ndim < 3):
raise TypeError((('%s: input must have dimension >= 3,... |
def fft(inp, norm=None):
"\n Performs the fast Fourier transform of a complex-valued input simulated by R^2.\n\n The input must be a real-valued variable of dimensions (m, ..., n, 2).\n It performs FFTs of size n along the last axis. \n\n The output is a tensor of dimensions (m, ..., n, 2).\n The r... |
def ifft(inp, norm=None):
"\n Performs the inverse fast Fourier Transform with complex-valued input simulated by R^2.\n\n The input is a variable of dimensions (m, ..., n, 2)\n The real and imaginary parts are stored as a\n pair of float arrays.\n\n The output is a real-valued variable of dimension... |
def _unitary(norm):
if (norm not in (None, 'ortho', 'no_norm')):
raise ValueError(("Invalid value %s for norm, must be None, 'ortho' or 'no norm'" % norm))
return norm
|
class FFT2Op(gof.Op):
__props__ = ()
def output_type(self, inp):
return T.TensorType(inp.dtype, broadcastable=([False] * inp.type.ndim))
def make_node(self, a, s=None):
a = T.as_tensor_variable(a)
if (a.ndim < 4):
raise TypeError((('%s: input must have dimension >= 4,... |
class IFFT2Op(gof.Op):
__props__ = ()
def output_type(self, inp):
return T.TensorType(inp.dtype, broadcastable=([False] * inp.type.ndim))
def make_node(self, a, s=None):
a = T.as_tensor_variable(a)
if (a.ndim < 4):
raise TypeError((('%s: input must have dimension >= 4... |
def fft2(inp, norm=None):
"\n Performs the fast Fourier transform of a complex-valued input simulated by R^2.\n\n The input must be a real-valued variable of dimensions (m, ..., n, 2).\n It performs FFT2s of size n along the last axis. \n\n The output is a tensor of dimensions (m, ..., n, 2).\n The... |
def ifft2(inp, norm=None):
"\n Performs the inverse fast Fourier Transform with complex-valued input simulated by R^2.\n\n The input is a variable of dimensions (m, ..., n, 2)\n The real and imaginary parts are stored as a\n pair of float arrays.\n\n The output is a real-valued variable of dimensio... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.