通过神经网络中的函数将数据从 2D 数组保存到文件中

Saving data from a 2d array into file through a function in neural network

本文关键字:2D 数组 数据 存到文件 神经网络 函数      更新时间:2023-10-16

我是神经网络的新手。我有2个功能。初始化权重并节省权重。当我初始化权重时,我还需要将它们保存在一个单独的文件中。

我有以下代码:

//Function for saving weights
void saveWeights(int Hidden, int Inputs, double arr[][?]){
  //double arr[][?];
  ofstream myfile;
  myfile.open("weights.txt");
     for(int j = 0;j<Hidden;j++){
        for(int i = 0;i<Inputs;i++){
            myfile<<arr[i][j]<<endl;
        }
     }
    myfile.close();
}
// set weights to random numbers
void initWeights(void){
     for(int j = 0;j<numHidden;j++){
        weightsHO[j] = getRand(0,1);
        for(int i = 0;i<numInputs;i++){
         weightsIH[i][j] = getRand(0,1);
         cout<<"Weights = "<<weightsIH[i][j]<<endl;
         saveWeights(numHidden, numInputs, weightsIH[i][j]);             
        }
      }
}

问题是我不知道为 2D 数组中的列传递什么值,因为它是一个可变长度数组。

你能指导一下该怎么做吗?

我还尝试了以下方法:

    //Function for saving weights
void saveWeights(double w){
  ofstream myfile;
  myfile.open("weights.txt");
            myfile<<w<<endl;
    myfile.close();
}
// set weights to random numbers
void initWeights(void){
     for(int j = 0;j<numHidden;j++){
        weightsHO[j] = getRand(0,1);
        for(int i = 0;i<numInputs;i++){
         weightsIH[i][j] = getRand(0,1);
         z = weightsIH[i][j];
         //cout<<"Weights = "<<weightsIH[i][j]<<endl;
         saveWeights(z);             
        }
      }
}

显示如何执行此操作的通用代码会很有帮助。提前感谢您的帮助。

有许多可能的解决方案。

1)将数组的维度写为文件中的第一个数字(一组数字)。

2) 写入文件时,在每行后插入NEW_LINE_CARACTER("",即 endl),并用空格分隔数字。

     for(int j = 0;j<Hidden;j++){
        for(int i = 0;i<Inputs;i++){
            myfile<<arr[i][j]<<" ";
        }
        myfile<<endl
     }

3) 使用尺寸等设置制作其他文件。

4) 使用与 C 样式数组不同的数据结构并尝试序列化。

等。