gpt4 book ai didi

c++ - FANN:使用从多个文件读取的数据训练 ANN 时发生内存泄漏

转载 作者:行者123 更新时间:2023-11-30 01:03:01 25 4
gpt4 key购买 nike

我有以下循环:

for (int i = 1; i <= epochs; ++i) {
for (std::vector<std::filesystem::path>::iterator it = batchFiles.begin(); it != batchFiles.end(); ++it) {
struct fann_train_data *data = fann_read_train_from_file(it->string().c_str());
fann_shuffle_train_data(data);
float error = fann_train_epoch(ann, data);
}
}

ann是网络。
batchFilesstd::vector<std::filesystem::path> .

此代码遍历文件夹中的所有训练数据文件,每次都使用它来训练 ANN,次数由 epochs 确定变量。

以下行会导致内存泄漏:

struct fann_train_data *data =
fann_read_train_from_file(it->string().c_str());

问题是我必须不断地在训练文件之间切换,因为我没有足够的内存来一次加载它们,否则我只会加载一次训练数据。

为什么会这样?我该如何解决这个问题?

最佳答案

在 C++ 中,当管理它的对象超出范围时,内存会自动释放。 (假设类(class)编写正确。)这叫做 RAII .

但 FANN 提供的是 C API,而不是 C++ API。在 C 中,您需要在用完内存后手动释放内存。推而广之,当 C 库为您创建一个对象时,它通常需要您在使用完该对象时告诉它。库没有很好的方法来自行确定何时应该释放对象的资源。

惯例是,每当 C API 为您提供类似 struct foo* create_foo() 的函数时,您应该寻找相应的函数,例如 void free_foo(struct foo* f) 。它是对称的。

在您的情况下,正如 PaulMcKenzie 最初指出的那样,您需要 void fann_destroy_train_data(struct fann_train_data * train_data)。来自 the documentation ,强调我的:

Destructs the training data and properly deallocates all of the associated data. Be sure to call this function after finished using the training data.

关于c++ - FANN:使用从多个文件读取的数据训练 ANN 时发生内存泄漏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54975525/

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