读取和修改caffemodel文件里的参数

  • Post author:
  • Post category:其他


基于caffe 的卷积神经网络模型训练后得到的权值是通过Google Protobuf来存储的后缀名为.caffemodel的二进制文件,这类文件一般很难直接打开进行权值的读取和修改。有的时候我们希望直观的看到网络中每个神经元的权值,或者希望更改网络的部分结构来得到新的结构进行finetune。在这样的情况下我们就需要对caffemodel文件进行操作。好在caffe的python接口提供了针对caffemodel文件的修改方法,用户可以从caffemodel文件中读取参数,并对参数进行修改以得到新的caffemodel文件。


1、读取caffemodel里的权值


首先caffe要先进行pycaffe 的编译并安装好pycaffe的依赖环境。然后用下述python文件可以查看caffemodel文件中各个层的参数,以查看lenet-5权值为例。

import caffe

if __name__ == "__main__":
	#文件的存放路径
	root = '/home/xhq11/caffe-master/examples/mnist/'
	caffe.set_mode_cpu
	net = caffe.Net(root+'lenet.prototxt',\
	root+'lenet_iter_10000.caffemodel',caffe.TEST')
	#第一个卷基层的权值
	conv1_w = net.params['conv1'][0].data
	#第一个卷基层的偏置值
	conv1_b = net.params['conv1'][1].data
	#可以打印相应的参数和参数的维度等信息
	print conv1_w,conv1_b
	print conv1_w.size,conv1_b.size

需要注意的是,这样的方法只能读取有训练参数层的权值,对于下采样、激活层等无训练参数的层,无法得到其层内权值(因为层内根本没有权值)。


2、修改caffemodel内的权值并保存为新的caffemodel


有的时候我们需要修改原caffemodel来得到新的caffemodel文件用于finetune等工作,可通过下述python文件实现,以修改lenet-5权值为例。

import caffe

if __name__ == "__main__":
	#文件的存放路径
	root = '/home/xhq11/caffe-master/examples/mnist/'
	caffe.set_mode_cpu
	net = caffe.Net(root+'lenet.prototxt',\
	root+'lenet_iter_10000.caffemodel',caffe.TEST')
	#在这部分做任何你希望的对权值的修改
	net.save('/path of your new caffemodel/newname.caffemodel')

但是这种方法的弊端也很明显,这种方法只能在原有的结构上进行权值的修改,而不能对原有结构进行修改,比如,删除原有结构中的某一层或增加新的层,或更改原有层的维度等。

在caffe 的官方文档中提供了一种修改caffemodel文件的方法,具体参考http://nbviewer.jupyter.org/github/BVLC/caffe/blob/master/examples/net_surgery.ipynb(需翻墙)。这里面的案例是讲caffenet的后三个全连接层(fc6/fc7/fc8)改成全卷基层(fc6-conv/fc7-conv/fc8-conv)以形成新的网络权值文件bvlc_caffenet_full_conv.caffemodel。值得注意的是,这里面的案例也仅仅是将原来后三个全连接层的权值“摊平”(文中的写法为flat)并赋给卷积层,由于全连接层和卷基层的参数个数是相同的,因此这个案例本质上也属于权值的进一步修改。文中最后有这么一段话:

Note that this model isn’t totally appropriate for sliding-window detection since it was trained for whole-image classification. Nevertheless it can work just fine. Sliding-window training and finetuning can be done by defining a sliding-window ground truth and loss such that a loss map is made for every location and solving as usual. (This is an exercise for the reader.)

caffe python API for inference:

import caffe

caffe.set_mode_cpu()

net =

caffe.Net

(‘xx.prototxt’,‘xx.caffemodel’,caffe.TEST)

net.blobs[‘data’].data[…] = xxx(inference data)

res = net.forward()

res即为网络的inference结果,保存为一个字典.



版权声明:本文为jiongjiongxia123原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。