pycaffe簡明文檔
by ChrisZZ, imzhuo@foxmail.com
2018年01月18日19:00:56
說明
caffe的python接口沒有官方說明文檔,例如查看一個函數的用法,pytorch能查到所有的用法,而pycaffe則需要自行去查看源碼。於是手動寫了一個很粗糙的文檔,湊合看了。
1.主要根據caffe_root/python/caffe
目錄下的__init__.py
和_caffe.cpp
來手動生成。
2.以及caffe_root/python/proto/caffe_pb2.py
文件(這個文件是從caffe.proto來的,特別大)。
3.還有就是caffe_root/python/caffe/test
目錄下的這些單元測試文件。
4.其他文件,如io.py
, net_spec.py
, pycaffe.py
, draw.py
, classifier.py
, detector.py
,要么是caffe_pb2.py
中眾多函數的重要的、有代表性的基本封裝和使用,要么就是充當(可能)常用的工具。
5.此外,老版本(如caffe-fast-rcnn)和新版本(如caffe-BVLC)的pycaffe支持的東西,肯定是新版本的多一些。本文檔僅僅列出了caffe-fast-rcnn版代碼中的函數,更新版本pycaffe中的函數需要自行查看_caffe.cpp
做對照理解。
也是醉了,其實可以直接查看從代碼和注釋生成的文檔的:
#在ipython環境下
import caffe
help(caffe.Net)
help(caffe.proto.caffe_pb2)
這里是模板:
className
類
className.funcName(param1, param2)
@param1 類型,作用
@param2 類型,作用
@descipion 函數的作用是,
@return 類型
caffe.Net
類
__init__(prototxt, phase)
@param prototxt: 字符串。指定prototxt路徑
@param phase: `caffe.TRAIN`或者`caffe.TEST`
@description: 根據prototxt初始化一個網絡。相當於C++的:
shared_ptr<Net<Dtype> > net(new Net<Dtype>(param_file,
static_cast<Phase>(phase)));
@return `Net`類對象,網絡實例
@example `net = caffe.Net('test.prototxt', caffe.TEST)`
__init__(prototxt, caffemodel, phase)
@param prototxt: 字符串。指定prototxt路徑
@param caffemodel: 字符串,指定caffemodel路徑
@param phase: `caffe.TRAIN`或者`caffe.TEST`
@description: 根據prototxt初始化一個網絡,並從caffemodel復制同名層的權值(作為網絡中該層的權值)。相當於C++的:
shared_ptr<Net<Dtype> > net(new Net<Dtype>(param_file,
static_cast<Phase>(phase)));
net->CopyTrainedLayersFrom(pretrained_param_file);
@return `Net`類對象,網絡實例
@example `net = caffe.Net('test.prototxt', 'resnet50.caffemodel', caffe.TEST)`
_forward(start, end)
@param start: int類型
@param end: int類型
@description: 執行前向傳播。調用的是C++的`Dtype Net<Dtype>::ForwardFromTo(int start, int end) `
@return: loss值
@example: 類的私有方法,所以不建議使用
_backward(start, end)
@param start: int類型
@param end: int類型
@description: 執行前向傳播。調用的是C++的`void Net<Dtype>::BackwardFromTo(int start, int end) `
@return: 沒有返回值。
@example: 類的私有方法,所以不建議使用
reshape()
@param: 不需要參數
@description: 網絡中的每一層,都執行reshape。調用的C++的`void Net<Dtype>::Reshape() `
@return: 沒有返回值類型
copy_from(caffemodel)
@param caffemodel: 字符串類型。指定(pretrained的)caffemodel路徑
@description: 讀取指定的caffemodel(二進制protobuf文件),從中讀取和當前網絡同名層的參數作為替代。調用的是C++`void Net<Dtype>::CopyTrainedLayersFrom(const string trained_filename)`
@return: 空
@example
pretrained_caffemodel = 'abc.caffemodel'
net = caffe.Net(prototxt, caffe.TEST)
net.copy_from(pretrained_caffemodel)
(來源:py-faster-rcnn)
copy_from(net)
@param net: (另一個)Net對象
@description: 從Net中讀取同名網絡層參數作為替代。調用的其實是`void Net<Dtype>::CopyTrainedLayersFrom(const NetParameter& param)`
@return 空
@example
net = caffe.Net(prototxt, caffe.TEST)
resnet = caffe.Net(prototxt_resnet, caffemodel, caffe.TEST)
net.copy_from(resnet)
share_with(net)
@param net: Net類型。打算從net上取同名層,和當前網絡共享參數。
@description: 和copy_from非常像。區別在於,被share的兩個Net對象,同名層的數據是共享的!也就是內存中只有一份!改了一個,另一個也被修改!調用的是C++`void Net<Dtype>::ShareTrainedLayersWith(const Net* other) `
@return 空
_blob_loss_weights
私有屬性。
返回loss函數中的每個blob的權值。按照blob_id進行索引。
_bottom_ids(i)
@param i: 層(layer)序號
@return 第i層的bottom們的id列表,`bottom_id_vecs_[i]`
_top_ids(i)
@param i: 層(layer)序號
@return 第i層的top們的id列表,`top_id_vecs_[i]`
_blobs
私有屬性
返回blobs(不是很懂!)
layers
公共屬性
返回layers
_blob_names
私有屬性
返回blob們的名字
_layer_names
私有屬性
返回layer們的名字
_inputs
私有屬性。
返回`net_input_blob_indices_`,也就是網絡輸入們的索引們
_outputs
私有屬性。
返回`net_output_blob_indices_`,也就是網絡輸出們的索引們
_set_input_arrays(?)
私有函數。
設定網絡輸入?(不懂)
save(pth)
@param pth: 字符串類型。指定保存的路徑。
@description: 保存當前網絡對象到文件(磁盤)。調用的是C++`void Net_Save(const Net<Dtype>& net, string filename) `
caffe.Blob
類
一開始我覺得這個類在pycaffe中沒有被暴露出來,因此沒用。
其實不是的。
某個layer的top或者bottom,其實都是Blob的實例。那么這些blob就需要查看相對應的屬性、函數。
shape
公開屬性
返回當前blob對象(也就是一個tensor)的各個維度信息
常見的:返回N,C,H,W
num
公開屬性
Deprecated legacy shape accessor num: use shape(0) instead.
channels
公開屬性
Deprecated legacy shape accessor channels: use shape(1) instead.
height
公開屬性
Deprecated legacy shape accessor height: use shape(2) instead.
width
公開屬性
Deprecated legacy shape accessor width: use shape(3) instead.
count
公開屬性
返回的是當前blob的維度數目,相當於len(self.shape)
比如,對於(N,C,H,W)維度的blob,返回的是4
reshape(shape_args)
公開函數
執行reshape操作
例子:
im = np.array(caffe.io.load_image('catGray.jpg', color=False)).squeeze()
im_input = im[np.newaxis, np.newaxis, :, :]
net.blobs['data'].reshape(*im_input.shape)
net.blobs['data'].data[...] = im_input
data
公開屬性
本質是`Blob<Dtype>::mutable_cpu_data`
diff
公開屬性
本質是`Blob<Dtype>::mutable_cpu_diff`
caffe.Layer
類
blobs
公開屬性
返回blobs
setup()
reshape()
phase
公開屬性
層的phase
type
公開屬性
層的type(??干什么用的?)
caffe.Solver
類
這個類沒有被直接暴露出來使用,而是被作為SGDSolver等子類繼承。因此子類中也有這些方法和屬性可用,需要查看。
注意
caffe.Solver類沒有構造函數!
但是caffe.Solver類的子類(例如caffe.SGDSolver)是有構造函數的!
net
公開屬性
Solver所擁有的net對象
test_nets
公開屬性
Solver所擁有的所有測試網絡(因此是一個列表)
iter
公開屬性
Solver對象當前迭代次數
solve(resume_file=None)
公開函數
讓當前Solver對象執行求解,也就是執行所有iter。
如果指定`resume_file`那么從該文件繼續執行(而不是從0次iter執行)
step(iters)
公開函數
@param iters: 需要執行的迭代次數
@description: 從Solver的當前迭代次數(self.iter)開始,執行iters次迭代。迭代期間可能輸出“平滑過的loss"(smoothed_loss),形如:
Iteration 20, loss = 3.66
具體見solver.cpp的`void Solver<Dtype>::UpdateSmoothedLoss(Dtype loss, int start_iter,
int average_loss)`函數
@return: 空
@example: solver.step(1) #執行一次迭代
restore(state_file)
公開函數
@param state_file: 字符串類型。暫存狀態文件的路徑。
@description: 從指定的暫存文件state_file中讀取(恢復)狀態。
snapshot()
公開函數
@description: 將當前solver的網路狀態寫入暫存文件(solver_state文件)
說明:暫存文件的名字是根據如下規則得到(C++):
`param_.snapshot_prefix() + "_iter_" + caffe::format_int(iter_) + ".caffemodel";`
可以通過python代碼進行查看(甚至修改snapshot的前綴??):
from caffe.proto import caffe_pb2
solver_param = caffe_pb2.SolverParameter()
print(solver_param.snapshot_prefix)
注意2(TODO):
caffe.SGDSolver.restore(), caffe.Net.copy_from(), caffe.SGDSolver.copy_from(), caffe.SGDSolver.step()等函數,使用前請參考https://github.com/BVLC/caffe/issues/3336
caffe.SGDSolver
類
caffe.Solver類的子類
__init__(filename)
@param filename: 字符串類型,指定SGDSolver的prototxt描述文件
@descrition 從指定的prototxt文件,創建SGDSolver
@example
solver_prototxt = 'resnet-50-test.prototxt'
self.solver = caffe.SGDSolver(solver_prototxt)
caffe.NesterovSolver
類
caffe.Solver類的子類
__init__(filename)
同SGDSolver的構造函數
caffe.AdaGradSolver
類
caffe.Solver類的子類
__init__(filename)
同SGDSolver的構造函數
caffe.RMSPropSolver
類
caffe.Solver類的子類
__init__(filename)
同SGDSolver的構造函數
caffe.AdaDeltaSolver
類
caffe.Solver類的子類
__init__(filename)
同SGDSolver的構造函數
caffe.AdamSolver
類
caffe.Solver類的子類
__init__(filename)
同SGDSolver的構造函數
caffe.get_solver(filename)
公開函數
@param filename: 字符串類型。指定的solver文件
@description: 從指定的solver文件,創建solver
caffe.set_mode_cpu()
caffe.set_mode_gpu()
caffe.set_device(gpu_id)
@param gpu_id: int類型
設定(gpu)id。從0開始。即:第一塊顯卡是0,第二塊顯卡是1.
caffe.set_random_seed()
設定隨機數種子。
好處:在重復實驗的時候,盡量減少隨機性。(但其實僅僅是種子一致,無法隨機數出現順序是一樣的,因此最后inference結果還是會不一樣,只不過波動性小了)
caffe.layer_type_list()
返回各個Layer的類型
caffe.proto.caffe_pb2
包
這個包下面有很多類。但是很多(也許是全部?)都是從caffe.proto
生成的,感覺很蛋疼啊,一個一個的寫,肯定寫不完的。
大概總結有這些:
LayerName
Parameter型,例如:SliceParameter
其他類:
反正,感覺都是在caffe.proto中通過message聲明的一個個東西,例如:
caffe.proto.caffe_pb2.SolverParameter類
message SolverParameter {
//////////////////////////////////////////////////////////////////////////////
// Specifying the train and test networks
//
// Exactly one train net must be specified using one of the following fields:
// train_net_param, train_net, net_param, net
// One or more test nets may be specified using any of the following fields:
// test_net_param, test_net, net_param, net
// If more than one test net field is specified (e.g., both net and
// test_net are specified), they will be evaluated in the field order given
// above: (1) test_net_param, (2) test_net, (3) net_param/net.
// A test_iter must be specified for each test_net.
// A test_level and/or a test_stage may also be specified for each test_net.
//////////////////////////////////////////////////////////////////////////////
// Proto filename for the train net, possibly combined with one or more
// test nets.
optional string net = 24;
// Inline train net param, possibly combined with one or more test nets.
optional NetParameter net_param = 25;
optional string train_net = 1; // Proto filename for the train net.
repeated string test_net = 2; // Proto filenames for the test nets.
optional NetParameter train_net_param = 21; // Inline train net params.
repeated NetParameter test_net_param = 22; // Inline test net params.
// The states for the train/test nets. Must be unspecified or
// specified once per net.
//
// By default, all states will have solver = true;
// train_state will have phase = TRAIN,
// and all test_state's will have phase = TEST.
// Other defaults are set according to the NetState defaults.
optional NetState train_state = 26;
repeated NetState test_state = 27;
// The number of iterations for each test net.
repeated int32 test_iter = 3;
// The number of iterations between two testing phases.
optional int32 test_interval = 4 [default = 0];
optional bool test_compute_loss = 19 [default = false];
// If true, run an initial test pass before the first iteration,
// ensuring memory availability and printing the starting value of the loss.
optional bool test_initialization = 32 [default = true];
optional float base_lr = 5; // The base learning rate
// the number of iterations between displaying info. If display = 0, no info
// will be displayed.
optional int32 display = 6;
// Display the loss averaged over the last average_loss iterations
optional int32 average_loss = 33 [default = 1];
optional int32 max_iter = 7; // the maximum number of iterations
// accumulate gradients over `iter_size` x `batch_size` instances
optional int32 iter_size = 36 [default = 1];
// The learning rate decay policy. The currently implemented learning rate
// policies are as follows:
// - fixed: always return base_lr.
// - step: return base_lr * gamma ^ (floor(iter / step))
// - exp: return base_lr * gamma ^ iter
// - inv: return base_lr * (1 + gamma * iter) ^ (- power)
// - multistep: similar to step but it allows non uniform steps defined by
// stepvalue
// - poly: the effective learning rate follows a polynomial decay, to be
// zero by the max_iter. return base_lr (1 - iter/max_iter) ^ (power)
// - sigmoid: the effective learning rate follows a sigmod decay
// return base_lr ( 1/(1 + exp(-gamma * (iter - stepsize))))
//
// where base_lr, max_iter, gamma, step, stepvalue and power are defined
// in the solver parameter protocol buffer, and iter is the current iteration.
optional string lr_policy = 8;
optional float gamma = 9; // The parameter to compute the learning rate.
optional float power = 10; // The parameter to compute the learning rate.
optional float momentum = 11; // The momentum value.
optional float weight_decay = 12; // The weight decay.
// regularization types supported: L1 and L2
// controlled by weight_decay
optional string regularization_type = 29 [default = "L2"];
// the stepsize for learning rate policy "step"
optional int32 stepsize = 13;
// the stepsize for learning rate policy "multistep"
repeated int32 stepvalue = 34;
// Set clip_gradients to >= 0 to clip parameter gradients to that L2 norm,
// whenever their actual L2 norm is larger.
optional float clip_gradients = 35 [default = -1];
optional int32 snapshot = 14 [default = 0]; // The snapshot interval
optional string snapshot_prefix = 15; // The prefix for the snapshot.
// whether to snapshot diff in the results or not. Snapshotting diff will help
// debugging but the final protocol buffer size will be much larger.
optional bool snapshot_diff = 16 [default = false];
enum SnapshotFormat {
HDF5 = 0;
BINARYPROTO = 1;
}
optional SnapshotFormat snapshot_format = 37 [default = BINARYPROTO];
// the mode solver will use: 0 for CPU and 1 for GPU. Use GPU in default.
enum SolverMode {
CPU = 0;
GPU = 1;
}
optional SolverMode solver_mode = 17 [default = GPU];
// the device_id will that be used in GPU mode. Use device_id = 0 in default.
optional int32 device_id = 18 [default = 0];
// If non-negative, the seed with which the Solver will initialize the Caffe
// random number generator -- useful for reproducible results. Otherwise,
// (and by default) initialize using a seed derived from the system clock.
optional int64 random_seed = 20 [default = -1];
// type of the solver
optional string type = 40 [default = "SGD"];
// numerical stability for RMSProp, AdaGrad and AdaDelta and Adam
optional float delta = 31 [default = 1e-8];
// parameters for the Adam solver
optional float momentum2 = 39 [default = 0.999];
// RMSProp decay value
// MeanSquare(t) = rms_decay*MeanSquare(t-1) + (1-rms_decay)*SquareGradient(t)
optional float rms_decay = 38;
// If true, print information about the state of the net that may help with
// debugging learning problems.
optional bool debug_info = 23 [default = false];
// If false, don't save a snapshot after training finishes.
optional bool snapshot_after_train = 28 [default = true];
// DEPRECATED: old solver enum types, use string instead
enum SolverType {
SGD = 0;
NESTEROV = 1;
ADAGRAD = 2;
RMSPROP = 3;
ADADELTA = 4;
ADAM = 5;
}
// DEPRECATED: use type instead of solver_type
optional SolverType solver_type = 30 [default = SGD];
}
caffe.proto.caffe_pb2.SolverState類
244 // A message that stores the solver snapshots
245 message SolverState {
246 optional int32 iter = 1; // The current iteration
247 optional string learned_net = 2; // The file that stores the learned net.
248 repeated BlobProto history = 3; // The history for sgd solvers
249 optional int32 current_step = 4 [default = 0]; // The current step for learning rate
250 }
總之,感受到了protobuf這個出自google的包的強大和可怕。