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

来源:互联网 发布:英语四级软件手机软件 编辑:程序博客网 时间:2024/05/07 04:56

如何使用生成的模型,可能是在训练好模型之后,需要考虑的问题。实际上,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)设置数据的初始化方式

# 加载ImageNetmu = 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 valuesprint '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×Wtransformer.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 netimage = caffe.io.load_image('image.jpg')# copy the image data into the memory allocated for the netnet.blobs['data'].data[...] = transformer.preprocess('data', image)### perform classificationoutput = net.forward()output_prob = output['prob'][0]  # the output probability vector for the first image in the batchprint 'predicted class is:', output_prob.argmax()

2 C++接口

0 0
原创粉丝点击