今天碰巧用到这个,遇到了一些问题,所以顺便记录下来。
直接使用train.sh中的方式,应该是行不通
比如如下的方式
#!/usr/bin/env sh
set -e
./build/tools/caffe train --solver=/***/adam_solver.prototxt --gpu=1,2,3
这样总会提示说 ImportError: No module named python.NormlizedMSE
使用python调用的方式
实际上faster rcnn也是这么做的,至于如何在调用c++二进制文件可执行文件的时候,仍能找到并执行python层,我也没有去深入研究,毕竟caffe对python的支持也不是全方位的,比如python调用多gpu就会有些问题。
继续说如何使用这种调用方式之前需要说明一些网上的错误操作
- 将自定义python层放到
caffe_root/python
下,如果找相关网页的话,能找到这样的有几篇{1,2}。 - 重新编译pycaffe:
make pycaffe
,比如1 - 还有一些其他不明所以的,可能是误打误撞碰对了吧3
知其然的做法
- solver的写法
import sys
sys.path.append('~/work/caffe_master/python') # for import caffe
sys.path.append('~/work/Myproject/train/') # for python layer, 这儿指明python的调用路径
import caffe
caffe.set_device(1)
caffe.set_mode_gpu()
solver=caffe.SGDSolver('~/work/Myproject/adam_solver.prototxt')
solver.solve()
- prototxt的写法
layer {
type: 'Python'
name: 'loss'
top: 'loss'
bottom: 'Dense3'
bottom: 'landmarks'
python_param {
# 自定义层模块的名字,注意,这儿一定是和上面solver中的路径相配合的
module: 'NormlizedMSE'
# the layer name -- the class name in the module
layer: 'NormlizedMSE'
}
# set loss weight so Caffe knows this is a loss layer.
# since PythonLayer inherits directly from Layer, this isn't automatically
# known to Caffe
loss_weight: 1
}
这儿是重点:NormlizedMSE.py 在路径’~/work/Myproject/train/'下,也就是用于训练的python文件中调用的函数。