gpt4 book ai didi

boost-serialization - 如何使用 Boost:serialization 来保存 Eigen::Matrix

转载 作者:行者123 更新时间:2023-12-04 22:22:40 24 4
gpt4 key购买 nike

你好,我有一个代码,它实现了 libeigen2 来计算特征向量。现在我想使用 boost::serialization 来保存信息以供以后检索。从示例 tutorial 我想出了以下代码!

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’

如何序列化 Eigen::Matrix 类?是否可以 ?
提前致谢。

最佳答案

您应该阅读有关 serializable 概念的 boost::serialization 文档。它基本上说类型需要是原始的或可序列化的。 Eigen 类型不是它,你的编译器试图告诉你。为了使特征类型可序列化,您需要实现以下免费功能

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

为了为 Eigen 做这件事,我想你可能会做这样的事情
模板

这是一个应该适合您的示例实现:
#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
}
}

关于boost-serialization - 如何使用 Boost:serialization 来保存 Eigen::Matrix,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12580579/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com