使用已训练好的caffe模型的步骤

如何使用生成的模型,可能是在训练好模型之后,需要考虑的问题。实际上,caffe是存在两种接口来进行调用模型:1种是基于python的,另一种则是基于c++的。我个人是倾向于使用python接口,因为:

谚语:人生苦短,我用python

最近刚好做了一个项目,同时开发了两种接口,所以也刚好来进行两者的比对。

0 前言

做任何事情之前,最好功利的问一问,做这件事情的目的是什么?如果你是一个如饥似渴的程序员,那更要如此。别盲目学习和做事情。

庄子云,吾生也有涯,而知也无涯,以有涯随无涯,殆己!

那么,为什么要实现接口调用caffe的模型呢?这是因为,模型已经训练好之后,需要使用模型来处理数据。对了,处理数据就是目的。那么,应该如何处理数据呢?

(1)是要对数据进行处理,使之与网络训练时输入的数据一样。因为,网络的接口对输入的数据是有一定的要求的。
(2)将数据调整好格式之后,需要确定是调用网络的那一部分来进行前向提取特征。所以需要devploy.proto文件来调用网络。
(3)则是要确定到底使用哪一层的特征。因为,有些网络是用来分类的,所以要提取最后分类的结果,而有些网络是用于提取特征的,因此则需要提取中间某一层的特征。
下面就以caffe官网的教程来进行分析应该如何使用训练好的caffe模型

1 python接口

(1)使用训练好的模型和前向文件devploy.proto来生成网络

#设置为cpu模式
caffe.set_mode_cpu()
#deploy.prototxt路径
model_def = caffe_root + 'models/bvlc_reference_caffenet/deploy.prototxt'
#训练好的caffemodel的路径
model_weights = caffe_root + 'models/bvlc_reference_caffenet/bvlc_reference_caffenet.caffemodel'
#生成网络
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)

(2)设置数据的初始化方式

# 加载ImageNet
mu = np.load(caffe_root + 'python/caffe/imagenet/ilsvrc_2012_mean.npy')
mu = mu.mean(1).mean(1)  # average over pixels to obtain the mean (BGR) pixel values
print 'mean-subtracted values:', zip('BGR', mu)

# create transformer for the input called 'data'
#创建transformer对象,用于将图像转换为适合于网络的方式,需要注意的是,如下的代码对象的成员初始化,而不是参数实际生效的顺序。
transformer = caffe.io.Transformer({'data': net.blobs['data'].data.shape})
# python读取的图片文件格式为H×W×K,需转化为K×H×W
transformer.set_transpose('data', (2,0,1))  
#设置均值
transformer.set_mean('data', mu)
# rescale from [0, 1] to [0, 255]            
transformer.set_raw_scale('data', 255)
# swap channels from RGB to BGR     
transformer.set_channel_swap('data', (2,1,0))  

(3)将网络前向并获取指定层的特征

# transform it and copy it into the net
image = caffe.io.load_image('image.jpg')

# copy the image data into the memory allocated for the net
net.blobs['data'].data[...] = transformer.preprocess('data', image)


### perform classification
output = net.forward()

output_prob = output['prob'][0]  # the output probability vector for the first image in the batch

print 'predicted class is:', output_prob.argmax()

2 C++接口

  • 2
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 5
    评论
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值