本文整理汇总了Python中caffe.set_mode_cpu方法的典型用法代码示例。如果您正苦于以下问题:Python caffe.set_mode_cpu方法的具体用法?Python caffe.set_mode_cpu怎么用?Python caffe.set_mode_cpu使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类caffe
的用法示例。
在下文中一共展示了caffe.set_mode_cpu方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: load_caffe
# 需要导入模块: import caffe [as 别名]
# 或者: from caffe import set_mode_cpu [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 set_mode_cpu [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 set_mode_cpu [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: predict
# 需要导入模块: import caffe [as 别名]
# 或者: from caffe import set_mode_cpu [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
示例5: load_caffe
# 需要导入模块: import caffe [as 别名]
# 或者: from caffe import set_mode_cpu [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
示例6: __init__
# 需要导入模块: import caffe [as 别名]
# 或者: from caffe import set_mode_cpu [as 别名]
def __init__(self,params):
self.dimension = params['dimension']
self.dataset = params['dataset']
self.pooling = params['pooling']
# Read image lists
with open(params['query_list'],'r') as f:
self.query_names = f.read().splitlines()
with open(params['frame_list'],'r') as f:
self.database_list = f.read().splitlines()
# Parameters needed
self.layer = params['layer']
self.save_db_feats = params['database_feats']
# Init network
if params['gpu']:
caffe.set_mode_gpu()
caffe.set_device(0)
else:
caffe.set_mode_cpu()
print "Extracting from:", params['net_proto']
cfg.TEST.HAS_RPN = True
self.net = caffe.Net(params['net_proto'], params['net'], caffe.TEST)
示例7: create_classifier
# 需要导入模块: import caffe [as 别名]
# 或者: from caffe import set_mode_cpu [as 别名]
def create_classifier(pretrained_model):
"""Creates a model from saved caffemodel file and returns a classifier."""
# Creates model from saved .caffemodel.
# The following file are shipped inside caffe-doc Debian package
model_def = os.path.join("/", "usr", "share", "doc", "caffe-doc",
"models","bvlc_reference_caffenet",
"deploy.prototxt")
image_dims = [ 256, 256 ]
# The following file are shipped inside python3-caffe-cpu Debian package
mean = np.load(os.path.join('/', 'usr', 'lib', 'python3',
'dist-packages', 'caffe', 'imagenet',
'ilsvrc_2012_mean.npy'))
channel_swap = [2, 1, 0]
raw_scale = 255.0
caffe.set_mode_cpu()
classifier = caffe.Classifier(model_def, pretrained_model,
image_dims=image_dims, mean=mean,
raw_scale=raw_scale,
channel_swap=channel_swap)
return classifier
示例8: setUp
# 需要导入模块: import caffe [as 别名]
# 或者: from caffe import set_mode_cpu [as 别名]
def setUp(self):
self.num_output = 13
net_f = simple_net_file(self.num_output)
f = tempfile.NamedTemporaryFile(delete=False)
f.write("""net: '""" + net_f + """'
test_iter: 10 test_interval: 10 base_lr: 0.01 momentum: 0.9
weight_decay: 0.0005 lr_policy: 'inv' gamma: 0.0001 power: 0.75
display: 100 max_iter: 100 snapshot_after_train: false""")
f.close()
self.solver = caffe.SGDSolver(f.name)
# also make sure get_solver runs
caffe.get_solver(f.name)
caffe.set_mode_cpu()
# fill in valid labels
self.solver.net.blobs['label'].data[...] = \
np.random.randint(self.num_output,
size=self.solver.net.blobs['label'].data.shape)
self.solver.test_nets[0].blobs['label'].data[...] = \
np.random.randint(self.num_output,
size=self.solver.test_nets[0].blobs['label'].data.shape)
os.remove(f.name)
os.remove(net_f)
示例9: setUp
# 需要导入模块: import caffe [as 别名]
# 或者: from caffe import set_mode_cpu [as 别名]
def setUp(self):
self.num_output = 13
net_f = simple_net_file(self.num_output)
f = tempfile.NamedTemporaryFile(mode='w+', delete=False)
f.write("""net: '""" + net_f + """'
test_iter: 10 test_interval: 10 base_lr: 0.01 momentum: 0.9
weight_decay: 0.0005 lr_policy: 'inv' gamma: 0.0001 power: 0.75
display: 100 max_iter: 100 snapshot_after_train: false
snapshot_prefix: "model" """)
f.close()
self.solver = caffe.SGDSolver(f.name)
# also make sure get_solver runs
caffe.get_solver(f.name)
caffe.set_mode_cpu()
# fill in valid labels
self.solver.net.blobs['label'].data[...] = \
np.random.randint(self.num_output,
size=self.solver.net.blobs['label'].data.shape)
self.solver.test_nets[0].blobs['label'].data[...] = \
np.random.randint(self.num_output,
size=self.solver.test_nets[0].blobs['label'].data.shape)
os.remove(f.name)
os.remove(net_f)
示例10: __init__
# 需要导入模块: import caffe [as 别名]
# 或者: from caffe import set_mode_cpu [as 别名]
def __init__(self, weights_path, image_net_proto, device_id=-1):
if device_id >= 0:
caffe.set_mode_gpu()
caffe.set_device(device_id)
else:
caffe.set_mode_cpu()
# Setup image processing net.
phase = caffe.TEST
self.image_net = caffe.Net(image_net_proto, weights_path, phase)
image_data_shape = self.image_net.blobs['data'].data.shape
self.transformer = caffe.io.Transformer({'data': image_data_shape})
channel_mean = np.zeros(image_data_shape[1:])
channel_mean_values = [104, 117, 123]
assert channel_mean.shape[0] == len(channel_mean_values)
for channel_index, mean_val in enumerate(channel_mean_values):
channel_mean[channel_index, ...] = mean_val
self.transformer.set_mean('data', channel_mean)
self.transformer.set_channel_swap('data', (2, 1, 0)) # BGR
self.transformer.set_transpose('data', (2, 0, 1))
示例11: load_network
# 需要导入模块: import caffe [as 别名]
# 或者: from caffe import set_mode_cpu [as 别名]
def load_network(proto_txt, caffe_model, device):
if 'gpu' in device:
caffe.set_mode_gpu()
device_id = int(device.split('gpu')[-1])
caffe.set_device(device_id)
else:
caffe.set_mode_cpu()
# load network
net = caffe.Net(proto_txt, caffe_model, caffe.TEST)
# tansformer
mu = np.load(osp.join(CAFFE_ROOT, 'models', 'ResNet', 'ResNet_mean.npy'))
mu = mu.mean(1).mean(1)
transformer = caffe.io.Transformer({'data': net.blobs['data'].data.shape})
transformer.set_transpose('data', (2, 0, 1)) # move image channels to outermost dimension
transformer.set_mean('data', mu) # subtract the dataset-mean value in each channel
transformer.set_raw_scale('data', 255) # rescale from [0, 1] to [0, 255]
transformer.set_channel_swap('data', (2, 1, 0)) # swap channels from RGB to BGR
# reshape input
net.blobs['data'].reshape(BS, 3, 224, 224)
return net, transformer
示例12: __init__
# 需要导入模块: import caffe [as 别名]
# 或者: from caffe import set_mode_cpu [as 别名]
def __init__(self, config_entry: dict, *args, **kwargs):
super().__init__(config_entry, *args, **kwargs)
self._delayed_model_loading = kwargs.get('delayed_model_loading', False)
caffe_launcher_config = LauncherConfigValidator(
'Caffe_Launcher', fields=self.parameters(), delayed_model_loading=self._delayed_model_loading
)
caffe_launcher_config.validate(self.config)
self._do_reshape = False
if not self._delayed_model_loading:
self.model, self.weights = self.automatic_model_search()
self.network = caffe.Net(str(self.model), str(self.weights), caffe.TEST)
self.allow_reshape_input = self.get_value_from_config('allow_reshape_input')
match = re.match(DEVICE_REGEX, self.get_value_from_config('device').lower())
if match.group('device') == 'gpu':
caffe.set_mode_gpu()
identifier = match.group('identifier') or 0
caffe.set_device(int(identifier))
elif match.group('device') == 'cpu':
caffe.set_mode_cpu()
self._batch = self.get_value_from_config('batch')
示例13: load_caffe
# 需要导入模块: import caffe [as 别名]
# 或者: from caffe import set_mode_cpu [as 别名]
def load_caffe(img_p, layers=50):
caffe.set_mode_cpu()
prototxt = "data/ResNet-%d-deploy.prototxt" % layers
caffemodel = "data/ResNet-%d-model.caffemodel" % layers
net = caffe.Net(prototxt, caffemodel, caffe.TEST)
net.blobs['data'].data[0] = img_p.transpose((2, 0, 1))
assert net.blobs['data'].data[0].shape == (3, 224, 224)
net.forward()
caffe_prob = net.blobs['prob'].data[0]
print_prob(caffe_prob)
return net
# returns the top1 string
示例14: read_caffemodel
# 需要导入模块: import caffe [as 别名]
# 或者: from caffe import set_mode_cpu [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)
示例15: load_weigths_from_caffe
# 需要导入模块: import caffe [as 别名]
# 或者: from caffe import set_mode_cpu [as 别名]
def load_weigths_from_caffe(self, protofile, caffemodel):
caffe.set_mode_cpu()
net = caffe.Net(protofile, caffemodel, caffe.TEST)
for name, layer in self.models.items():
if isinstance(layer, nn.Conv2d):
caffe_weight = net.params[name][0].data
layer.weight.data = torch.from_numpy(caffe_weight)
if len(net.params[name]) > 1:
caffe_bias = net.params[name][1].data
layer.bias.data = torch.from_numpy(caffe_bias)
continue
if isinstance(layer, nn.BatchNorm2d):
caffe_means = net.params[name][0].data
caffe_var = net.params[name][1].data
layer.running_mean = torch.from_numpy(caffe_means)
layer.running_var = torch.from_numpy(caffe_var)
# find the scale layer
top_name_of_bn = self.layer_map_to_top[name][0]
scale_name = ''
for caffe_layer in self.net_info['layers']:
if caffe_layer['type'] == 'Scale' and caffe_layer['bottom'][0] == top_name_of_bn:
scale_name = caffe_layer['name']
break
if scale_name != '':
caffe_weight = net.params[scale_name][0].data
layer.weight.data = torch.from_numpy(caffe_weight)
if len(net.params[name]) > 1:
caffe_bias = net.params[scale_name][1].data
layer.bias.data = torch.from_numpy(caffe_bias)