| 1 |
//------------------------------------------------------------------------------ |
| 2 |
// name: knn2-search.ck |
| 3 |
// desc: basic k-nearest-neighbor (k-NN) search example; it simulates a |
| 4 |
// simplified musical genre classification task where three labeled |
| 5 |
// categories are given respective locations in a 2D feature space. |
| 6 |
// |
| 7 |
// version: need chuck version 1.5.0.0 or higher |
| 8 |
// sorting: part of ChAI (ChucK for AI) |
| 9 |
// |
| 10 |
// uncomment the next line to learn more about the KNN2 object: |
| 11 |
// KNN2.help(); |
| 12 |
// |
| 13 |
// author: Yikai Li and Ge Wang |
| 14 |
// date: Spring 2023 |
| 15 |
//------------------------------------------------------------------------------ |
| 16 |
|
| 17 |
// create a k-NN object |
| 18 |
KNN2 knn; |
| 19 |
|
| 20 |
// prepare data: labels |
| 21 |
["classical", "pop", "rock"] @=> string labelNames[]; |
| 22 |
// prepare data: using 2-dimensional feature space for this example; |
| 23 |
// in general, the feature space could be much higher |
| 24 |
[[0.0, 0.0], |
| 25 |
[1.0, 1.0], |
| 26 |
[2.0, 2.0]] @=> float features[][]; |
| 27 |
// prepare data: corresponding IDs between labels and features |
| 28 |
[0, 1, 2] @=> int labels[]; |
| 29 |
// number of labels |
| 30 |
labels.size() => int NUM_LABELS; |
| 31 |
// train the model |
| 32 |
knn.train( features, labels ); |
| 33 |
// optional: weigh the feature dimensions |
| 34 |
[1.0, 1.0] @=> float weights[]; |
| 35 |
// optional: set the weights across feature dimensions |
| 36 |
knn.weigh( weights ); |
| 37 |
|
| 38 |
// provide an unlabled test query |
| 39 |
[0.5, 0.5] @=> float q[]; |
| 40 |
|
| 41 |
// search for nearest neighbor label |
| 42 |
int neighbor_labels[0]; |
| 43 |
// corresponding indices |
| 44 |
int neighbor_indices[0]; |
| 45 |
|
| 46 |
// search type #1: get labels |
| 47 |
knn.search( q, 1 , neighbor_labels ); |
| 48 |
chout <= "query=(" + q[0] + ", " + q[1] + "); k=1:\n" + labelNames[neighbor_labels[0]] <= IO.newline(); |
| 49 |
|
| 50 |
// search type #2: get labels and indices |
| 51 |
knn.search( q, 2 , neighbor_labels, neighbor_indices ); |
| 52 |
chout <= "\n" <= "query=(" + q[0] + ", " + q[1] + "); k=2:\n"; |
| 53 |
for (int i; i < 2; i++) |
| 54 |
{ |
| 55 |
chout <= labelNames[neighbor_labels[i]] + " [" + neighbor_indices[i] + "]" <= IO.newline(); |
| 56 |
} |
| 57 |
|
| 58 |
// search for nearest neighbor label and feature |
| 59 |
float neighbor_features[2][2]; |
| 60 |
knn.search( q, 2 , neighbor_labels, neighbor_indices, neighbor_features ); |
| 61 |
chout <= "\n" <= "query=(" + q[0] + ", " + q[1] + "); k=2:\n"; |
| 62 |
for (int i; i < 2; i++) |
| 63 |
{ |
| 64 |
chout <= labelNames[neighbor_labels[i]] + " [" + neighbor_indices[i] + "]" + |
| 65 |
" (" + neighbor_features[i][0] + ", " + neighbor_features[i][1] + ")" <= IO.newline(); |
| 66 |
} |
| 67 |
|
| 68 |
|