2012-09-25 90 views
4

你好我有一個代碼實現libeigen2來計算特徵向量。現在我想使用boost :: serialization來保存信息以供稍後檢索。從示例tutorial我想出了以下代碼!如何使用Boost:序列化來保存Eigen :: Matrix

class RandomNode { 
private: 
friend class boost::serialization::access; 
template<class Archive> 
void serialize(Archive & ar, const unsigned int version) 
{ 
    ar & is_leaf_; 
    ar & depth_; 
    ar & num_classes_; 
    ar & num_features_; 
    // Split node members 
    ar & random_feature_indices_; 
    ar & random_feature_weights_; 
    ar & threshold_; 
    ar & leftChild_; 
    ar & rightChild_; 

} 
bool is_leaf_; 
int depth_; 
int num_classes_; 
int num_features_; 

// Split node members 
VectorXi random_feature_indices_; 
VectorXd random_feature_weights_; 
double threshold_; 
RandomNode* leftChild_; 
RandomNode* rightChild_; 
// Methods and so on 
} 

現在,當我嘗試運行這段代碼,我得到以下錯誤

/usr/include/boost/serialization/access.hpp:118:9: error: ‘class Eigen::Matrix<double, 10000, 1>’ has no member named ‘serialize’ 

我如何序列化徵:: Matrix類?可能嗎 ? 在此先感謝。

+0

http://stackoverflow.com/questions/18382457/eigen-and-boostserialize – iNFINITEi

回答

12

您應該閱讀關於serializable概念主題的boost :: serialization文檔。它基本上說類型需要是原始的或者可序列化的。 Eigen類型不是,它是你的編譯器試圖告訴你的。爲了使本徵類型的序列化,你將需要實現以下免費功能

template<class Archive> 
inline void serialize(
    Archive & ar, 
    my_class & t, 
    const unsigned int file_version 
) { 
    ... 
} 

爲了做到這一點對艾根,我想你會做這樣的事情 模板

下面是一個例子實施這應該適合你:

#include <fstream> 
#include <Eigen/Core> 
#include <boost/archive/text_oarchive.hpp> 

using namespace Eigen; 

struct RandomNode { 
friend class boost::serialization::access; 
template<class Archive> 
void serialize(Archive & ar, const unsigned int version) 
{ 
    ar & random_feature_indices_; 
    ar & random_feature_weights_; 
} 
// Split node members 
VectorXi random_feature_indices_; 
VectorXd random_feature_weights_; 
}; 

namespace boost 
{ 
template<class Archive, typename _Scalar, int _Rows, int _Cols, int _Options, int _MaxRows, int _MaxCols> 
inline void serialize(
    Archive & ar, 
    Matrix<_Scalar, _Rows, _Cols, _Options, _MaxRows, _MaxCols> & t, 
    const unsigned int file_version 
) 
{ 
    size_t rows = t.rows(), cols = t.cols(); 
    ar & rows; 
    ar & cols; 
    if(rows * cols != t.size()) 
    t.resize(rows, cols); 

    for(size_t i=0; i<t.size(); i++) 
    ar & t.data()[i]; 
} 
} 

int main() 
{ 
    // create and open a character archive for output 
    std::ofstream ofs("filename"); 

    RandomNode r; 
    r.random_feature_indices_.resize(3,1); 

    // save data to archive 
    { 
     boost::archive::text_oarchive oa(ofs); 
     // write class instance to archive 
     oa << r; 
     // archive and stream closed when destructors are called 
    } 
}