Skip to content

Commit

Permalink
libshogun simple kNN example with random data
Browse files Browse the repository at this point in the history
  • Loading branch information
iglesias committed Jul 8, 2013
1 parent 2a59ace commit 28e5183
Show file tree
Hide file tree
Showing 3 changed files with 62 additions and 2 deletions.
1 change: 1 addition & 0 deletions examples/undocumented/libshogun/Makefile
Expand Up @@ -27,6 +27,7 @@ TARGETS = basic_minimal \
classifier_qda \
classifier_lda \
classifier_multiclasslinearmachine \
classifier_knn \
kernel_gaussian kernel_revlin kernel_custom\
library_dyn_int library_gc_array library_indirect_object \
library_hash parameter_set_from_parameters \
Expand Down
59 changes: 59 additions & 0 deletions examples/undocumented/libshogun/classifier_knn.cpp
@@ -0,0 +1,59 @@
/*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* Written (W) 2013 Fernando J. Iglesias García
*/

#include <shogun/distance/EuclideanDistance.h>
#include <shogun/features/DataGenerator.h>
#include <shogun/features/DenseFeatures.h>
#include <shogun/labels/MulticlassLabels.h>
#include <shogun/multiclass/KNN.h>

using namespace shogun;

#define NUM 10
#define DIMS 2
#define CLASSES 4
#define k 3

int main(int, char*[])
{
init_shogun_with_defaults();

#ifdef HAVE_LAPACK /* because of CDataGenerator::generate_gaussians */

// Labels and features containers
SGVector<float64_t> lab(CLASSES*NUM);
SGMatrix<float64_t> feat(DIMS, CLASSES*NUM);
// Random generation of features
feat = CDataGenerator::generate_gaussians(NUM,CLASSES,DIMS);
// Labels
for (int32_t i = 0; i < CLASSES; ++i)
for (int32_t j = 0; j < NUM; ++j)
lab[i*NUM + j] = i;

// Create train labels
CMulticlassLabels* labels = new CMulticlassLabels(lab);
// Create train features
CDenseFeatures<float64_t>* features = new CDenseFeatures<float64_t>(feat);

// Create KNN classifier
CKNN* knn = new CKNN(k, new CEuclideanDistance(features, features), labels);
// Train classifier
knn->train();
// Apply classifier
CMulticlassLabels* output = CLabelsFactory::to_multiclass( knn->apply() );

// Free memory
SG_UNREF(knn)
SG_UNREF(output)

#endif /* HAVE_LAPACK */

exit_shogun();
return 0;
}
4 changes: 2 additions & 2 deletions src/shogun/multiclass/KNN.cpp
Expand Up @@ -123,10 +123,10 @@ SGMatrix<int32_t> CKNN::nearest_neighbors()
{
SG_PROGRESS(i, 0, n)

//lhs idx 0..n-1 (i.e., all train examples) and rhs idx i
//lhs idx 0..num train examples-1 (i.e., all train examples) and rhs idx i
distances_lhs(dists,0,m_train_labels.vlen-1,i);

//fill in an array with 0, 1,2, ..., num train examples
//fill in an array with 0..num train examples-1
for (int32_t j=0; j<m_train_labels.vlen; j++)
train_idxs[j]=j;

Expand Down

0 comments on commit 28e5183

Please sign in to comment.