当前位置: 首页>>代码示例>>Python>>正文


Python caffe.TEST属性代码示例

本文整理汇总了Python中caffe.TEST属性的典型用法代码示例。如果您正苦于以下问题:Python caffe.TEST属性的具体用法?Python caffe.TEST怎么用?Python caffe.TEST使用的例子?那么恭喜您, 这里精选的属性代码示例或许可以为您提供帮助。您也可以进一步了解该属性所在caffe的用法示例。


在下文中一共展示了caffe.TEST属性的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: load_caffe

# 需要导入模块: import caffe [as 别名]
# 或者: from caffe import TEST [as 别名]
def load_caffe(model_desc, model_file):
    """
    Load a caffe model. You must be able to ``import caffe`` to use this
    function.

    Args:
        model_desc (str): path to caffe model description file (.prototxt).
        model_file (str): path to caffe model parameter file (.caffemodel).
    Returns:
        dict: the parameters.
    """
    with change_env('GLOG_minloglevel', '2'):
        import caffe
        caffe.set_mode_cpu()
        net = caffe.Net(model_desc, model_file, caffe.TEST)
    param_dict = CaffeLayerProcessor(net).process()
    logger.info("Model loaded from caffe. Params: " +
                ", ".join(sorted(param_dict.keys())))
    return param_dict 
开发者ID:tensorpack,项目名称:dataflow,代码行数:21,代码来源:loadcaffe.py

示例2: prep_net

# 需要导入模块: import caffe [as 别名]
# 或者: from caffe import TEST [as 别名]
def prep_net(self, gpu_id, prototxt_path='', caffemodel_path=''):
        import caffe
        print('gpu_id = %d, net_path = %s, model_path = %s' % (gpu_id, prototxt_path, caffemodel_path))
        if gpu_id == -1:
            caffe.set_mode_cpu()
        else:
            caffe.set_device(gpu_id)
            caffe.set_mode_gpu()
        self.gpu_id = gpu_id
        self.net = caffe.Net(prototxt_path, caffemodel_path, caffe.TEST)
        self.net_set = True

        # automatically set cluster centers
        if len(self.net.params[self.pred_ab_layer][0].data[...].shape) == 4 and self.net.params[self.pred_ab_layer][0].data[...].shape[1] == 313:
            print('Setting ab cluster centers in layer: %s' % self.pred_ab_layer)
            self.net.params[self.pred_ab_layer][0].data[:, :, 0, 0] = self.pts_in_hull.T

        # automatically set upsampling kernel
        for layer in self.net._layer_names:
            if layer[-3:] == '_us':
                print('Setting upsampling layer kernel: %s' % layer)
                self.net.params[layer][0].data[:, 0, :, :] = np.array(((.25, .5, .25, 0), (.5, 1., .5, 0), (.25, .5, .25, 0), (0, 0, 0, 0)))[np.newaxis, :, :]

    # ***** Call forward ***** 
开发者ID:junyanz,项目名称:interactive-deep-colorization,代码行数:26,代码来源:colorize_image.py

示例3: __init__

# 需要导入模块: import caffe [as 别名]
# 或者: from caffe import TEST [as 别名]
def __init__(self, model_weights, model_def, threshold=0.5, GPU_MODE=False):
        if GPU_MODE:
            caffe.set_device(0)
            caffe.set_mode_gpu()
        else:
            caffe.set_mode_cpu()
        self.net = caffe.Net(model_def,  # defines the structure of the model
                        model_weights,  # contains the trained weights
                        caffe.TEST)  # use test mode (e.g., don't perform dropout)
        self.threshold = threshold
        self.transformer = caffe.io.Transformer({'data': self.net.blobs['data'].data.shape})
        self.transformer.set_transpose('data', (2, 0, 1))
        self.transformer.set_mean('data', np.array([127.0, 127.0, 127.0]))  # mean pixel
        self.transformer.set_raw_scale('data',
                                  255)  # the reference model operates on images in [0,255] range instead of [0,1]
        self.transformer.set_channel_swap('data', (2, 1, 0))  # the reference model has channels in BGR order instead of RGB
        image_resize = 300
        self.net.blobs['data'].reshape(1, 3, image_resize, image_resize) 
开发者ID:Hzzone,项目名称:Hand-Keypoint-Detection,代码行数:20,代码来源:ssd_net.py

示例4: _initialize_caffe

# 需要导入模块: import caffe [as 别名]
# 或者: from caffe import TEST [as 别名]
def _initialize_caffe(deploy_file, input_weight_file, training_mean_pickle, inference_width,
            inference_height):
    """
    Initializes Caffe to prepare to run some data through the model for inference.
    """
    caffe.set_mode_gpu()
    net = caffe.Net(deploy_file, input_weight_file, caffe.TEST)

    # input preprocessing: 'data' is the name of the input blob == net.inputs[0]
    transformer = caffe.io.Transformer({"data": net.blobs["data"].data.shape})
    # PIL.Image loads the data with the channel last.
    transformer.set_transpose("data", (2, 0, 1))
    # Mean pixel.
    transformer.set_mean("data", np.load(training_mean_pickle).mean(1).mean(1))
    # The reference model operates on images in [0, 255] range instead of [0, 1].
    transformer.set_raw_scale("data", 255)
    # The reference model has channels in BGR order instead of RGB.
    transformer.set_channel_swap("data", (2, 1, 0))

    net.blobs["data"].reshape(1, 3, inference_height, inference_width)

    return (net, transformer) 
开发者ID:BradNeuberg,项目名称:cloudless,代码行数:24,代码来源:predict.py

示例5: add_batchnormscale

# 需要导入模块: import caffe [as 别名]
# 或者: from caffe import TEST [as 别名]
def add_batchnormscale(self, input, name):

        if True: # necessary?
            batch_norm_param = {'moving_average_fraction': 0.95, 'use_global_stats': True}
            param = [dict(lr_mult=0), dict(lr_mult=0), dict(lr_mult=0)]
            l = L.BatchNorm(input, name=name + '_bn', batch_norm_param=batch_norm_param, param=param, include={'phase': caffe.TEST}, ntop=1)
            setattr(self.net_spec, name + '_bn', l)

            batch_norm_param = {'moving_average_fraction': 0.95, 'use_global_stats': False}
            l = L.BatchNorm(input, name=name + '_bn', top=name + '_bn', batch_norm_param=batch_norm_param, param=param, include={'phase': caffe.TRAIN}, ntop=0)
            setattr(self.net_spec, name + '_bn' + '_train', l)

            l = L.Scale(getattr(self.net_spec, name + '_bn'), scale_param={'bias_term': True})
            setattr(self.net_spec, name, l)
        else: # here without split in use_global_stats True/False
            l = L.Scale(L.BatchNorm(input), scale_param={'bias_term': True})
            setattr(self.net_spec, name, l)

        return l 
开发者ID:peterneher,项目名称:peters-stuff,代码行数:21,代码来源:CaffeUNet_3D.py

示例6: add_batchnormscale

# 需要导入模块: import caffe [as 别名]
# 或者: from caffe import TEST [as 别名]
def add_batchnormscale(self, input, name):

        if True : # necessary?
            batch_norm_param={'moving_average_fraction': 0.95, 'use_global_stats': True }
            param = [dict(lr_mult=0),dict(lr_mult=0),dict(lr_mult=0)]
            l = L.BatchNorm(input, name=name+'_bn', batch_norm_param=batch_norm_param, param=param, include={'phase': caffe.TEST}, ntop=1)
            setattr(self.net_spec, name+'_bn', l)

            batch_norm_param={'moving_average_fraction': 0.95, 'use_global_stats': False }
            l = L.BatchNorm(input, name=name+'_bn', top=name+'_bn', batch_norm_param=batch_norm_param, param=param, include={'phase': caffe.TRAIN}, ntop=0)
            setattr(self.net_spec, name+'_bn' + '_train', l)

            l = L.Scale(getattr(self.net_spec, name+'_bn'), scale_param = { 'bias_term': True } )
            setattr(self.net_spec, name, l)
        else : # here without split in use_global_stats True/False
            l = L.Scale(L.BatchNorm(input), scale_param={'bias_term': True})
            setattr(self.net_spec, name, l)

        return l 
开发者ID:peterneher,项目名称:peters-stuff,代码行数:21,代码来源:CaffeUNet_2D.py

示例7: _load_pretrained_phocnet

# 需要导入模块: import caffe [as 别名]
# 或者: from caffe import TEST [as 别名]
def _load_pretrained_phocnet(self, phocnet_bin_path, gpu_id, debug_mode, deploy_proto_path, phoc_size):
        # create a deploy proto file
        self.logger.info('Saving PHOCNet deploy proto file to %s...', deploy_proto_path)
        mpg = ModelProtoGenerator(initialization='msra', use_cudnn_engine=gpu_id is not None)
        proto = mpg.get_phocnet(word_image_lmdb_path=None, phoc_lmdb_path=None, phoc_size=phoc_size, generate_deploy=True)
        with open(deploy_proto_path, 'w') as proto_file:
            proto_file.write(str(proto))
            
        # create the Caffe PHOCNet object
        self.logger.info('Creating PHOCNet...')
        if debug_mode:
            phocnet = caffe.Net(deploy_proto_path, phocnet_bin_path, caffe.TEST)
        else:
            with Suppressor():
                phocnet = caffe.Net(deploy_proto_path, phocnet_bin_path, caffe.TEST)
        return phocnet 
开发者ID:ssudholt,项目名称:phocnet,代码行数:18,代码来源:phocnet_evaluator.py

示例8: main

# 需要导入模块: import caffe [as 别名]
# 或者: from caffe import TEST [as 别名]
def main():
	args = parse_args()
	sys.path.append(args.caffe_root)
	import caffe
	net = caffe.Net(args.caffe_proto, args.caffe_model, caffe.TEST)
	print dir(net.layers[1].blobs[0])
	# for i, x in enumerate(net._layer_names):
	# 	print x, net.layers[i].type,
	# 	if x in net.params:
	# 		print net.params[x][0].shape
	# 	print '\n'
	model = bulid(net)
	torch.save(model.state_dict(), args.caffe_proto.split('.')[0]+'.pth')
	f = open(args.caffe_proto.split('.')[0]+'.py', 'w')
	stdout = sys.stdout
	sys.stdout = f
	print 'model = ', model
	sys.stdout = stdout
	f.close() 
开发者ID:pkuCactus,项目名称:BDCN,代码行数:21,代码来源:caffe2pytorch.py

示例9: net

# 需要导入模块: import caffe [as 别名]
# 或者: from caffe import TEST [as 别名]
def net(weights=WEIGHTS):
    """
    Get the caffe net that has been trained to segment facade features.

    This initializes or re-initializes the global network with weights. There are certainly side-effects!

    The weights default to a caffe model that is part of the same sourcecode repository as this file.
    They can be changed by setting the I12_WEIGHTS environment variable, by passing a command line argument
    to some programs, or programatically (of course).

    :param weights: The weights to use for the net.
    :return:
    """
    global WEIGHTS
    global _net
    if _net is None or weights != WEIGHTS:
        if weights is not None:
            WEIGHTS = weights
        _net = caffe.Net(LAYERS, WEIGHTS, caffe.TEST)
    return _net 
开发者ID:jfemiani,项目名称:facade-segmentation,代码行数:22,代码来源:model.py

示例10: predict

# 需要导入模块: import caffe [as 别名]
# 或者: from caffe import TEST [as 别名]
def predict(sound_file, prototxt, model, output_path):

  image_files = wav_to_images(sound_file, output_path)

  caffe.set_mode_cpu()
  net = caffe.Classifier(prototxt, model,
                         #image_dims=(224, 224)
                         #channel_swap=(2,1,0),
                         raw_scale=255 # convert 0..255 values into range 0..1
                         #caffe.TEST
                        )

  input_images = np.array([caffe.io.load_image(image_file, color=False) for image_file in image_files["melfilter"]])
  #input_images = np.swapaxes(input_images, 1, 3)

  #prediction = net.forward_all(data=input_images)["prob"]

  prediction = net.predict(input_images, False)  # predict takes any number of images, and formats them for the Caffe net automatically

  print prediction
  print 'prediction shape:', prediction[0].shape
  print 'predicted class:', prediction[0].argmax()
  print image_files

  return prediction 
开发者ID:twerkmeister,项目名称:iLID,代码行数:27,代码来源:predict.py

示例11: TestCaffe

# 需要导入模块: import caffe [as 别名]
# 或者: from caffe import TEST [as 别名]
def TestCaffe(proto_path, model_path, inputs, LayerCheck, ModelInd):
    net = caffe.Net(proto_path, model_path, caffe.TEST)
    net.blobs['data'].data[...] = inputs
    print('input blob:')
    print(net.blobs['data'].data[...])

    net.forward()

    if LayerCheck == 'Softmax_1':
        PrintLabel(net.blobs[LayerCheck].data[0].flatten())
    else:
        print(net.blobs[LayerCheck].data[0][...].flatten())
        if (ModelInd == 17):
            result_img = net.blobs[LayerCheck].data[0] * 255
            result_img = result_img.astype(int)
            result_img = np.transpose(result_img, (1, 2, 0))
            result_img = result_img[..., ::-1]
            cv2.imwrite("AnimeNet_result.png", result_img)
        if (ModelInd == 91):
            result_img = net.blobs[LayerCheck].data[0] * 255
            result_img = result_img.astype(int)
            result_img = np.transpose(result_img, (1, 2, 0))
            result_img = result_img[..., ::-1]
            cv2.imwrite("Upsample_result.png", result_img) 
开发者ID:starimeL,项目名称:PytorchConverter,代码行数:26,代码来源:test.py

示例12: inference

# 需要导入模块: import caffe [as 别名]
# 或者: from caffe import TEST [as 别名]
def inference(cls, architecture_name, architecture, path, image_path):
        if cls.sanity_check(architecture_name):
            import caffe
            import numpy as np
            net = caffe.Net(architecture[0], architecture[1], caffe.TEST)

            func = TestKit.preprocess_func['caffe'][architecture_name]
            img = func(image_path)
            img = np.transpose(img, (2, 0, 1))
            img = np.expand_dims(img, 0)
            net.blobs['data'].data[...] = img
            predict = np.squeeze(net.forward()[net._output_list[-1]][0])
            predict = np.squeeze(predict)
            return predict

        else:
            return None 
开发者ID:microsoft,项目名称:MMdnn,代码行数:19,代码来源:extractor.py

示例13: test

# 需要导入模块: import caffe [as 别名]
# 或者: from caffe import TEST [as 别名]
def test(net_caffe,net_torch,data_np,data_torch,args):
    blobs_caffe, rsts_caffe = forward_caffe(net_caffe, data_np)
    blobs_torch, rsts_torchs = forward_torch(net_torch, data_torch)
    # test the output of every layer
    for layer, value in blobs_caffe.items():
        if layer in blobs_torch:
            value_torch = blobs_torch[layer]
            value = value[0]
            if value.size!=value_torch.size:continue
            if 'relu' in layer: continue
            try:
                np.testing.assert_almost_equal(value, value_torch, decimal=args.decimal)
                print("TEST layer {}: PASS".format(layer))
            except:
                print("TEST layer {}: FAIL".format(layer))
                # np.testing.assert_almost_equal(np.clip(value, min=0), np.clip(value_torch, min=0))
    # test the output
    print("TEST output")
    for rst_caffe,rst_torch in zip(rsts_caffe,rsts_torchs):
        np.testing.assert_almost_equal(rst_caffe, rst_torch, decimal=args.decimal)
    print("TEST output: PASS") 
开发者ID:hahnyuan,项目名称:nn_tools,代码行数:23,代码来源:testify_pytorch_to_caffe_example.py

示例14: __init__

# 需要导入模块: import caffe [as 别名]
# 或者: from caffe import TEST [as 别名]
def __init__(self, net_proto, net_weights, device_id, input_size=None):
        caffe.set_mode_gpu()
        caffe.set_device(device_id)
        self._net = caffe.Net(net_proto, net_weights, caffe.TEST)

        input_shape = self._net.blobs['data'].data.shape

        if input_size is not None:
            input_shape = input_shape[:2] + input_size

        transformer = caffe.io.Transformer({'data': input_shape})

        if self._net.blobs['data'].data.shape[1] == 3:
            transformer.set_transpose('data', (2, 0, 1))  # move image channels to outermost dimension
            transformer.set_mean('data', np.array([104, 117, 123]))  # subtract the dataset-mean value in each channel
        else:
            pass # non RGB data need not use transformer

        self._transformer = transformer

        self._sample_shape = self._net.blobs['data'].data.shape 
开发者ID:yjxiong,项目名称:temporal-segment-networks,代码行数:23,代码来源:action_caffe.py

示例15: read_caffemodel

# 需要导入模块: import caffe [as 别名]
# 或者: from caffe import TEST [as 别名]
def read_caffemodel(prototxt_fname, caffemodel_fname):
    """Return a caffe_pb2.NetParameter object that defined in a binary
    caffemodel file
    """
    if use_caffe:
        caffe.set_mode_cpu()
        net = caffe.Net(prototxt_fname, caffemodel_fname, caffe.TEST)
        layer_names = net._layer_names
        layers = net.layers
        return (layers, layer_names)
    else:
        proto = caffe_pb2.NetParameter()
        with open(caffemodel_fname, 'rb') as f:
            proto.ParseFromString(f.read())
        return (get_layers(proto), None) 
开发者ID:awslabs,项目名称:dynamic-training-with-apache-mxnet-on-aws,代码行数:17,代码来源:caffe_parser.py


注:本文中的caffe.TEST属性示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。