本文整理匯總了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
示例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 *****
示例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)
示例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)
示例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
示例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
示例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
示例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()
示例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
示例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
示例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)
示例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
示例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")
示例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
示例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)