| 1 |
//------------------------------------------------------------------------------ |
| 2 |
// name: knn2-search.ck |
| 3 |
// desc: basic k-nearest-neighbor (k-NN) search example; |
| 4 |
// |
| 5 |
// version: need chuck version 1.5.0.0 or higher |
| 6 |
// sorting: part of ChAI (ChucK for AI) |
| 7 |
// |
| 8 |
// uncomment the next line to learn more about the KNN object: |
| 9 |
// KNN.help(); |
| 10 |
// |
| 11 |
// author: Yikai Li and Ge Wang |
| 12 |
// date: Spring 2023 |
| 13 |
//------------------------------------------------------------------------------ |
| 14 |
|
| 15 |
// create a KNN object |
| 16 |
KNN knn; |
| 17 |
|
| 18 |
// prepare data: using 2-dimensional feature space for this example; |
| 19 |
// in general, the feature space could be much higher |
| 20 |
[[0.0, 0.0], |
| 21 |
[1.0, 1.0], |
| 22 |
[2.0, 2.0]] @=> float features[][]; |
| 23 |
// train the model |
| 24 |
knn.train( features ); |
| 25 |
// optional: weigh feature dimensions |
| 26 |
[1.0, 1.0] @=> float weights[]; |
| 27 |
// optional: set the weights across dimensions |
| 28 |
knn.weigh( weights ); |
| 29 |
|
| 30 |
// provide a test query |
| 31 |
[0.5, 0.5] @=> float q[]; |
| 32 |
|
| 33 |
// corresponding indices |
| 34 |
int neighbor_indices[0]; |
| 35 |
|
| 36 |
// search |
| 37 |
knn.search( q, 2 , neighbor_indices ); |
| 38 |
chout <= "query = ("+ q[0]+","+q[1]+"); k=2: ["+ neighbor_indices[0]+","+neighbor_indices[1]+"]" <= IO.newline(); |