// declare the parameter, normally put it in header file. structMyParam : public dmlc::Parameter<MyParam> { float learning_rate; int num_hidden; int activation; std::string name; // declare parameters DMLC_DECLARE_PARAMETER(MyParam) { DMLC_DECLARE_FIELD(num_hidden).set_range(0, 1000) .describe("Number of hidden unit in the fully connected layer."); DMLC_DECLARE_FIELD(learning_rate).set_default(0.01f) .describe("Learning rate of SGD optimization."); DMLC_DECLARE_FIELD(activation).add_enum("relu", 1).add_enum("sigmoid", 2) .describe("Activation function type."); DMLC_DECLARE_FIELD(name).set_default("layer") .describe("Name of the net."); } };
// register the parameter, this is normally in a cc file. DMLC_REGISTER_PARAMETER(MyParam);
从以上代码可知,不同之处是在 DMLC_DECLARE_PARAMETER(MyParam) 后面这一部分,这部分声明了所有的字段。这个例子声明了 float, int 和 string 类型的参数。这个实例代码的特点是:
// This is an example program showing usage of parameter module // Build, on root folder, type // // make example // // Example usage: // // example/parameter num_hidden=100 name=aaa activation=relu //
#include<dmlc/parameter.h>
structMyParam : public dmlc::Parameter<MyParam> { float learning_rate; int num_hidden; int activation; std::string name; // declare parameters in header file DMLC_DECLARE_PARAMETER(MyParam) { DMLC_DECLARE_FIELD(num_hidden).set_range(0, 1000) .describe("Number of hidden unit in the fully connected layer."); DMLC_DECLARE_FIELD(learning_rate).set_default(0.01f) .describe("Learning rate of SGD optimization."); DMLC_DECLARE_FIELD(activation).add_enum("relu", 1).add_enum("sigmoid", 2) .describe("Activation function type."); DMLC_DECLARE_FIELD(name).set_default("mnet") .describe("Name of the net.");
// user can also set nhidden besides num_hidden DMLC_DECLARE_ALIAS(num_hidden, nhidden); DMLC_DECLARE_ALIAS(activation, act); } };
// register it in cc file DMLC_REGISTER_PARAMETER(MyParam);
// declare the parameter, normally put it in header file. structMyParam : public dmlc::Parameter<MyParam> { float learning_rate; int num_hidden; // declare parameters DMLC_DECLARE_PARAMETER(MyParam) { DMLC_DECLARE_FIELD(num_hidden); DMLC_DECLARE_FIELD(learning_rate).set_default(0.01f); } };
// register the parameter, this is normally in a cc file. DMLC_REGISTER_PARAMETER(MyParam);
structParameter<MyParam> { template<typename ValueType> inline FieldEntry<ValueType>& DECLARE(ParamManagerSingleton<MyParam> *manager, const std::string& key, ValueType& ref){ // offset gives a generic way to access the address of the field // from beginning of the structure. size_t offset = ((char*)&ref - (char*)this); parameter::FieldEntry<ValueType> *e = new parameter::FieldEntry<ValueType>(key, offset); manager->AddEntry(key, e); return *e; } };
// This code is only used to show the general idea. // This code will only run once, the real code is done via singleton declaration pattern. { static ParamManagerSingleton<MyParam> manager; MyParam tmp; tmp->__DECLARE__(&manager); }