Knn using Java

asked 2015-11-19 16:07:58 -0500

jigsawjigsaw gravatar image

updated 2015-12-03 09:02:03 -0500

Hi, I'm trying to implement a toy example using knn classification techniques in Java.

    //Here I create my training data
    Mat trainData = new Mat(new Size(4,6), CvType.CV_32F);

    for(int i =0; i<trainData.rows();i++) {
        for (int j= 0; j < trainData.cols(); j++) {
            trainData.put(i,j,i+2);
        } 
    }
    System.out.println("TRAINDATA_DUMP: "+ trainData.dump());
    //        TRAINDATA_DUMP: [2, 2, 2, 2;
                    //         3, 3, 3, 3;
                    //         4, 4, 4, 4;
                    //         5, 5, 5, 5;
                    //         6, 6, 6, 6;
                    //         7, 7, 7, 7]

    //Here I created matrices to be used in the training and find nearest part of knn
    Mat sampleIdx = new Mat(new Size(1, 6), CvType.CV_8U);   
    Mat results = new Mat(new Size (1, 6), CvType.CV_32F);
    Mat nearests = new Mat(new Size (1, 6), CvType.CV_32F);
    Mat dists = new Mat(new Size (1, 6), CvType.CV_32F);

   //Here I create my training labels
    for(int i =0; i<sampleIdx.rows();i++) {
        sampleIdx.put(i,0,i+2);
    }
    System.out.println("sampleIdx: "+ sampleIdx.dump());
    //sampleIdx: [2;
    //            3;
    //            4;
    //            5;
    //            6;
    //            7]

    CvKNearest knn = new CvKNearest();

    //Here I trained the data using the empty matrix created above, the training labels, false for classification, 6 for maxK and false for updateBase
    boolean trained = knn.train(trainData,results, sampleIdx,false,6,false);

    //Here I introduced a test vector
    Mat testFeature = new Mat(new Size(4,1), CvType.CV_32F);
    for(int i =0; i<testFeature.rows();i++) {
        for(int j =0; j<testFeature.cols();j++) {
            testFeature.put(i,j,3); //testFeature: [3, 3, 3, 3]
        }
    }

    //Here I used findnearest with the test feature, with K = 1, storing results, nearests and dists in the matrices created above
    float response =  knn.find_nearest(testFeature, 1,results, nearests, dists);

    System.out.println("results: "+ results.dump());      //results: [0]
    System.out.println("nearests: "+ nearests.dump());    //nearests: [0]
    System.out.println("dists: "+ dists.dump());          //dists: [0]
    System.out.println("response: "+ response);           //response: 0.0

Nearests is supposed to give out the label of the nearest feature vector [3] and dists is suppose to give out the distances between the test and the training. I've been looking all over for examples, and messed around with parameters, and different sizes of matrices. Any help is really really appreciated! Thanks in advance!

edit retag flag offensive close merge delete