存储对象以供将来使用(在重新启动程序时)

Store object for future use (On Restarting Program)

我正在用 C++ 实现类似于神经网络的东西。学习后,我留下了一个具有特定权重和 int 节点之间相互连接的网络。有什么方法可以存储这个学到的网络以供将来使用吗?

我能想到的唯一方法是创建一个遍历每个节点的程序,将权重和连接存储到一个文件中,然后在我想使用它时重新创建网络。我打算这样做,但我想知道是否有更好的解决方案?

我的意思是在堆上创建一个网络,"learn",然后将其存储为一个文件。这样我以后就可以不用经过学习过程就可以使用这个我后来学的网络。

我要存储的 class 有一个 std::tuple 的 std::vector,其中包含指针和浮点数。 我要存储的这个 class 也是由其他 class 组成的。

听起来您可以将其存储在提升 属性 树中(它可以将自身写入 xml 或 json)。

下面的示例假设您首先将指针转换为索引。那是;我假设每个节点都有一个数字,然后 pointer 只是指向该节点的另一个索引。

我同意许多评论者建议检查升压序列化(特别是关于指针),但对于您描述的问题和小数据,这会很有效。 按照目前的情况,它写入了大约 25000 nodes/second(仅),对于 1e4 个节点,文件大小约为 15MB。

#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/json_parser.hpp>
#include <tuple>
#include <vector>

int main() {

    using boost::property_tree::ptree;

    using Node = std::tuple<double, size_t, size_t>;
    std::vector<Node> nodes;

    // example filling
    nodes.emplace_back(0.1, 1, 1);
    nodes.emplace_back(1.1, 2, 1);
    nodes.emplace_back(2.1, 1, 3);
    nodes.emplace_back(3.1, 0, 2);

    ptree pt_nodes;

    for (auto i = size_t(0); i < nodes.size() ; ++i) {
        const auto& node = nodes[i];
        ptree pt_node;
        pt_node.put("id", i);
        pt_node.put("w0", std::get<0>(node));
        pt_node.put("ptrA", std::get<1>(node));
        pt_node.put("ptrB", std::get<2>(node));
        pt_nodes.push_back(std::make_pair("node"+std::to_string(i), pt_node));
    }

    ptree pt_all;
    pt_all.add_child("nodes", pt_nodes);
    write_json("test1.json", pt_all);

结果是这样的:

 {
    "nodes":
    {
        "node0":
        {
            "id": "0",
            "w0": "0.1",
            "ptrA": "1",
            "ptrB": "1"
        },
        "node1":
        {
            "id": "1",
            "w0": "1.1",
            "ptrA": "2",
            "ptrB": "1"
        },
        "node2":
        {
            "id": "2",
            "w0": "2.1",
            "ptrA": "1",
            "ptrB": "3"
        },
        "node3":
        {
            "id": "3",
            "w0": "3.1",
            "ptrA": "0",
            "ptrB": "2"
        }
    }
}

将其读回向量:

ptree pt_in;
read_json("test1.json", pt_in);
const auto pt_in_nodes = pt_in.get_child("nodes");
std::vector<Node> in_nodes(pt_in_nodes.size(), {});

for (const auto iter : pt_in_nodes)
{
    const auto ind = iter.second.get<size_t>("id");
    const auto w0 = iter.second.get<double>("w0");
    const auto ptrA= iter.second.get<size_t>("ptrA");
    const auto ptrB= iter.second.get<size_t>("ptrB");
    //std::cout << "id: " << ind << std::endl;
    //std::cout << "w0: " << w0 << std::endl;
    //std::cout << "ptrA: " << w1<< std::endl;
    //std::cout << "ptrB: " << ptr << std::endl;
    in_nodes.at(ind) = std::make_tuple(w0,ptrA,ptrB);
}