C++ 实现text格式数据集的读取

这段代码主要展示了如何使用C++读取文件的行数和列数,以及对数据进行标准化(归一化)处理。在读取文件时,分别计算了以换行符分隔的行数和通过流提取的列数。此外,还包含了内存管理和数据读取的函数,如读取MNIST数据集的特征和标签,以及对数据进行标准差归一化。
摘要由CSDN通过智能技术生成

读取行

// 逐行读取文件计数,得到输入文件的行数
    int getFileRows(const char *fileName) {
        std::ifstream fileStream;
        std::string tmp;
        int count = 0;// 行数计数器
        fileStream.open(fileName);
        if (fileStream.fail()) {//文件打开失败:返回0
            return 0;
        } else {//文件存在
            while (getline(fileStream, tmp, '\n')) {//读取一行
                if (tmp.size() > 0)
                    count++;
            }
            fileStream.close();
            return count;
        }
    }

读取列

// 逐行读取文件计数,得到输入文件的列数
    int getFileColumns(const char *fileName) {
        std::ifstream fileStream;
        fileStream.open(fileName);

        double tmp = 0;
        int count = 0;    // 列数计数器
        char cc, aa;            //当前位置的字符
        cc = fileStream.peek();
        while (('\n' != cc) && (!fileStream.eof())) { // 指针指向的当前字符,仅观测,不移动指针位置
            fileStream >> tmp;
            ++count;
            cc = fileStream.peek();
            if ('\n' != cc) {
                fileStream >> aa;
            }
        }
        fileStream.close();
        return count;
    }

读取训练数据

// 逐行读取文件计数,得到输入文件的列数
    int getFileColumns(const char *fileName) {
        std::ifstream fileStream;
        fileStream.open(fileName);

        double tmp = 0;
        int count = 0;    // 列数计数器
        char cc, aa;            //当前位置的字符
        cc = fileStream.peek();
        while (('\n' != cc) && (!fileStream.eof())) { // 指针指向的当前字符,仅观测,不移动指针位置
            fileStream >> tmp;
            ++count;
            cc = fileStream.peek();
            if ('\n' != cc) {
                fileStream >> aa;
            }
        }
        fileStream.close();
        return count;
    }

释放内存

 void MNIST::FreeData(COMPUTE_TYPE **x, COMPUTE_TYPE **y) {
        if (x && *x) delete[] *x;
        if (y && *y) delete[] *y;
    }

    void MNIST::FreeData(double **x, double **y) {
        if (x && *x) delete[] *x;
        if (y && *y) delete[] *y;
    }

读取测试数据

 int MNIST::ReadTestData(double **x, double **y) {
        MPC_OPTION &mp = *MPC_OPTION::GetMPCOption();
        int nFeatures, nLabels;
        mp.local_n = getFileRows((const char *) mp.test_feature_path);
        mp.local_d -= 1;
        nFeatures = ReadFeatures(x, (const char *) mp.test_feature_path);
        nLabels = ReadLabels(y, (const char *) mp.test_label_path);
        if (nFeatures != mp.d || nLabels <= 0) return -1;
        mp.nTest = nLabels;
        mp.d = nFeatures;
        return 0;
    }

读取特征

 int MNIST::ReadFeatures(double **x, const char *filename) {
        MPC_OPTION &mp = *MPC_OPTION::GetMPCOption();
        if (x == NULL) return -1;

        //judge if input number of n and d out of the range of dataset
        int realFeatures = getFileColumns(filename);
        int reallables = getFileRows(filename);
        int number_of_features = mp.local_d;
        int number_of_lables = mp.local_n;
        if (number_of_features > realFeatures || number_of_features <= 0) {
            Log(DEBUG_INFO, "input data_d out of range");
            return -1;
        }
        if (number_of_lables > reallables || number_of_lables <= 0) {
            Log(DEBUG_INFO, "input data_n out of range");
            return -1;
        }

        std::ifstream fileStream;
        fileStream.open(filename);

        if (!fileStream) {
            Log(DEBUG_INFO, "[ReadFeatures] cannot open file:%s\n", filename);
            //std::cout<<"Unable to open file";
            return -1;
        }
        if (fileStream.is_open()) {
            double tmp = 0;    //当前位置上的数值
            int colCount = 0;            // 列数计数器
            int index = 0;        // X[]数组的下标
            int maxIndex = (number_of_features + 1) * number_of_lables;
            char douhao;
            double *xx = new double[maxIndex];
            while (!fileStream.eof()) {
                fileStream >> tmp;
                if (index < maxIndex) {
                    xx[index] = tmp;
                    //Log(DEBUG_INFO, "tmp: %.4f.", xx[index]);
                    index++;
                } else break;

                if (colCount + 1 != number_of_features && '\n' != fileStream.peek()) // 未到行尾,colCount累加
                {
                    ++colCount;
                    fileStream >> douhao;

                } else //已到行尾,colCount清零
                {
                    colCount = 0;    // 列数清零
                    while ('\n' != fileStream.peek()) {
                        fileStream >> douhao;
                        fileStream >> tmp;
                    }
                    xx[index] = 1;
                    index++;
                }
            }
            double *xxx = new double[maxIndex];
            stdnorm(xxx, xx);
            *x = new double[maxIndex];
            for (int i = 0; i < maxIndex; i++) {
                (*x)[i] = xxx[i] * (double) (1 << mp.fraction_bits);  //turn xx to xxx can do stdnorm
            }
            //DoubleToFixPoint(*x, xxx, maxIndex);

            // 关闭文件
            delete[]xx;
            delete[]xxx;
            fileStream.close();
            return number_of_features + 1;
        }
        return 0;
    }

读取标签

 int MNIST::ReadLabels(double **y, const char *filename) {
        MPC_OPTION &mp = *MPC_OPTION::GetMPCOption();
        if (y == NULL) return -1;

        //judge if input number of n out of the range of dataset
        int reallables = getFileRows(filename);
        int number_of_lables = mp.local_n;
        if (number_of_lables > reallables || number_of_lables <= 0) {
            Log(DEBUG_INFO, "input data_n out of range");
            return -1;
        }


        std::ifstream fileStream;
        fileStream.open(filename);

        if (!fileStream) {
            Log(DEBUG_INFO, "[ReadFeatures] cannot open file:%s\n", filename);
            //std::cout<<"Unable to open file";
            return -1;
        }
        if (fileStream.is_open()) {
            double tmp = 0;    //当前位置上的数值
            int colCount = 0;            // 列数计数器
            int index = 0;        // X[]数组的下标
            int maxIndex = mp.local_n;
            char douhao;
            double *yy = new double[maxIndex];
            while (!fileStream.eof()) {
                fileStream >> tmp;
                if (index < maxIndex) {
                    yy[index] = tmp;
                    //cout << (*X)[index] << endl;
                    index++;
                } else {
                    break;
                }

                if (colCount + 1 != 1 && '\n' != fileStream.peek()) // 未到行尾,colCount累加
                {
                    ++colCount;
                    fileStream >> douhao;

                } else //已到行尾,colCount清零
                {
                    colCount = 0;    // 列数清零
                    while ('\n' != fileStream.peek()) {
                        fileStream >> douhao;
                        fileStream >> tmp;
                    }
                }
            }
            *y = new double[maxIndex];
            for (int i = 0; i < maxIndex; i++) {
                (*y)[i] = yy[i] * (double) (1 << mp.fraction_bits);
            }
            //DoubleToFixPoint(*y, yy, maxIndex);
            // 关闭文件
            fileStream.close();
            delete[]yy;
            return number_of_lables;
        }
        return 0;
    }

数据标准化(归一化)

void MNIST::stdnorm(double *out, double *in) {
        MPC_OPTION &mp = *MPC_OPTION::GetMPCOption();
        double *ave = new double[mp.local_d];
        memset(ave, 0, mp.local_d * sizeof(double));
        for (int i = 0; i < mp.local_d; i++) {
            for (int j = 0; j < mp.local_n; j++) {
                ave[i] += in[j * (mp.local_d + 1) + i];
            }
            ave[i] /= mp.local_n;
        }
        //for(int i=0 ;i<mp.local_d;i++){
        //	Log(DEBUG_INFO, "mean per Features:%.4f ", ave[i]);
        //}

        double *sqrt1 = new double[mp.local_d];
        memset(sqrt1, 0, mp.local_d * sizeof(double));
        for (int i = 0; i < mp.local_d; i++) {
            for (int j = 0; j < mp.local_n; j++) {
                sqrt1[i] += ((in[j * (mp.local_d + 1) + i] - ave[i]) * (in[j * (mp.local_d + 1) + i] - ave[i]));
            }
            sqrt1[i] /= mp.local_n;
        }

        //for(int i=0 ;i<mp.local_d ;i++){
        //	Log(DEBUG_INFO, "sqrt per Features:%.4f ", sqrt1[i]);
        //}

        for (int i = 0; i < (mp.local_d + 1); i++) {
            for (int j = 0; j < mp.local_n; j++) {
                if (i == mp.local_d) {
                    out[j * (mp.local_d + 1) + i] = 1;
                } else if (sqrt1[i] == 0) out[j * (mp.local_d + 1) + i] = in[j * (mp.local_d + 1) + i];
                else out[j * (mp.local_d + 1) + i] = (in[j * (mp.local_d + 1) + i] - ave[i]) / sqrt1[i];
            }
        }

        //for(int i=0 ;i<22 ;i++){  
        //	Log(DEBUG_INFO, "22 changed data:%.4f ", out[i]);
        //}

        delete[]ave;
        delete[]sqrt1;
    }

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
为了实现一个类似于ChatGPT的AI对话系统,需要进行以下步骤: 1. 定义一个文本文件,用于训练模型。可以选择使用公开可用的数据集,如Cornell电影对话语料库或Ubuntu对话语料库等。 2. 使用C++14的STL库读取文本文件数据,并将其转换为模型的输入格式。这通常涉及将文本分成单词或字符,并将其转换为数字向量。 3. 定义一个神经网络模型,可以使用C++14的深度学习库,如TensorFlow或Caffe等。 4. 使用模型对输入数据进行训练,以便能够预测下一个单词或字符。在训练期间,可以使用反向传播算法来优化模型参数。 5. 在模型训练完成后,可以使用它来生成AI对话。这涉及将用户输入转换为模型的输入格式,并根据模型的预测输出生成响应文本。 以下是一个简单的C++14代码示例,用于读取文本文件并将其转换为数字向量: ```c++ #include <iostream> #include <fstream> #include <sstream> #include <vector> #include <string> #include <unordered_map> using namespace std; // 定义一个函数,用于将文本转换为数字向量 vector<int> text_to_vector(string text, unordered_map<string, int> word_to_index) { vector<int> result; stringstream ss(text); string word; while (ss >> word) { if (word_to_index.find(word) != word_to_index.end()) { result.push_back(word_to_index[word]); } } return result; } int main() { // 读取文本文件 ifstream file("data.txt"); string line; vector<string> data; while (getline(file, line)) { data.push_back(line); } file.close(); // 建立词汇表 unordered_map<string, int> word_to_index; int index = 0; for (string text : data) { stringstream ss(text); string word; while (ss >> word) { if (word_to_index.find(word) == word_to_index.end()) { word_to_index[word] = index++; } } } // 将文本转换为数字向量 vector<vector<int>> input_data; for (string text : data) { input_data.push_back(text_to_vector(text, word_to_index)); } // 输出结果 for (vector<int> input : input_data) { for (int i : input) { cout << i << " "; } cout << endl; } return 0; } ``` 这段代码将文本文件`data.txt`的每一行读入一个字符串向量,然后将这些字符串向量转换为数字向量。数字向量是一个整数向量,每个元素对应于词汇表的一个单词。在这个例子,我们使用了一个无序映射将每个单词映射到一个唯一的整数。 请注意,这只是一个简单的例子,实现一个完整的AI对话系统需要更多的代码和复杂的算法
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值