ML Loading from .csv File ( C++ , OpenCV )

asked 2018-04-24 13:26:25 -0600

I am tring to get result from OpenCV SVM algorithm. First, it loads data from .csv file then it split the file data and labels as Mat. but machine learning algorithms doesn't give an output properly. My Data Classification labels are 0.0 and 1.0 but outputs are 1.0737418e+009 and 1,06533532e+0009. But if it initialize data from code it works perfect. What is the problem?

Initialize :

int labels[4] = {1, -1, -1, -1};
float trainingData[4][2] = { {501, 10}, {255, 10}, {501, 255}, {10, 501} };
Mat trainingDataMat(4, 2, CV_32FC1, trainingData);
Mat labelsMat(4, 1, CV_32SC1, labels);
// OpenCV ML prediction

The other side is loading data .csv file to vector then spliting data and label part in to mat.

void loadFromCSV(const std::string filename, vector<vector<std::string>>& matrix, char del){

std::ifstream file(filename.c_str());
std::vector<std::string> row;
std::string line;
std::string cell;

cout<<"loadFromCSV :" << filename << endl;

string line1;

        while (getline(file,line))
            {
            Size_row++;
            stringstream lineStream(line);
            row.clear();

            while (getline(lineStream,cell,del))
            {
            row.push_back(cell);
            Size_col++;
        }

    if(!row.empty()){
    matrix.push_back(row);
                      }
              }
}


void SplitData_Mat(vector<vector<std::string>>& ML_matrix, cv::Mat& Data, cv::Mat& Labels, int ML_row, int ML_col){

std::vector<std::vector<std::string>> matrix = ML_matrix;

const char *ML_Labels[2] = {"1" ,"2"};

    Data = Mat(ML_row,ML_col-1, CV_32FC1);
    Labels = Mat(ML_row,1,CV_32SC1);

    for (int i = 0; i < ML_row; i++)
    {

        for (int j = 0; j < ML_col-1; j++)
        {

            Data.at<float>(i,j) = stof(matrix[i][j].c_str());

        }

    float labelId;
    if (matrix[i][ML_col-1]==ML_Labels[0])
        {
        labelId = 0.0;

        }
    else if (matrix[i][ML_col-1]==ML_Labels[1])
        {
        labelId = 1.0;

        }

    Labels.at<float>(i,0)=labelId;

    }
}
edit retag flag offensive close merge delete

Comments

1

you dont need to write your own csv parser, have a look here

(and maybe show us an example line of your csv)

also: Labels.at<float>(i,0)=labelId; <-- int, not float

berak gravatar imageberak ( 2018-04-24 20:47:29 -0600 )edit