无法在Dlib中序列化学习函数

时间:2017-11-08 09:19:59

标签: c++ serialization dlib

我有一个来自dlib库的修改示例。我正在尝试训练one_vs_one_trainer并序列化派生函数。这是我的代码示例:

typedef matrix<double, 2, 1> SampleType;
typedef radial_basis_kernel<SampleType> Kernel;
typedef normalized_function<one_vs_one_decision_function<one_vs_one_trainer<any_trainer<SampleType>>>> LearnedFunction;

std::vector<double> labels; 
std::vector<SampleType> samples;

for (int r = -20; r <= 20; ++r)
{
    for (int c = -20; c <= 20; ++c)
    {
        SampleType samp(2);
        samp(0) = r;
        samp(1) = c;
        samples.push_back(samp);

        if (sqrt((double)r*r + c*c) <= 5)
            labels.push_back(1.0);
        else if (sqrt((double)r*r + c*c) <= 10)
            labels.push_back(2.0);
        else
            labels.push_back(3.0);

    }
}

vector_normalizer<SampleType> normalizer;
normalizer.train(samples);
for (auto& s : samples) {
    s = normalizer(s);
}

one_vs_one_trainer<any_trainer<SampleType>> trainer;
krr_trainer<Kernel> rbf_trainer;
rbf_trainer.set_kernel(Kernel(0.1));
trainer.set_trainer(rbf_trainer);

LearnedFunction learnedFunction;
learnedFunction.normalizer = normalizer;
learnedFunction.function = trainer.train(samples, labels);

serialize("saved_function.dat") << learnedFunction;

但是,最后一行会抛出错误:

terminate called after throwing an instance of 'dlib::serialization_error'
  what():  Can't serialize one_vs_one_decision_function.  Not all decision functions defined.
   while serializing an object of type one_vs_one_decision_function
   while serializing object of type normalized_function

你知道序列化失败的原因吗?我感谢任何帮助。

1 个答案:

答案 0 :(得分:1)

由于@ davis-king的评论,我找到了解决方案。我需要指定决策函数的类型:

typedef normalized_function<
    one_vs_one_decision_function<
        one_vs_one_trainer<any_trainer<SampleType>>, decision_function<Kernel>
>> LearnedFunction;