| 1 |
//------------------------------------------------------------------------------ |
| 2 |
// name: knn2-classify.ck |
| 3 |
// desc: k-nearest-neighbor (k-NN) classification 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 classifier |
| 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 unlabeled test query |
| 39 |
[0.5, 0.5] @=> float q[]; |
| 40 |
|
| 41 |
// predict with new query and k=1 |
| 42 |
predict( q, 1 ); |
| 43 |
// predict with the same query and k=2 |
| 44 |
predict( q, 2 ); |
| 45 |
|
| 46 |
// based on a new unlabeled test query and its distance to its |
| 47 |
// k nearest neighbors, predict and print the probabilities of |
| 48 |
// class membership NOTE: for the sake of the example, this |
| 49 |
// function assumes query has 2 dimensions |
| 50 |
fun void predict( float query[], int k ) |
| 51 |
{ |
| 52 |
// how we get the data back |
| 53 |
float prob[NUM_LABELS]; |
| 54 |
|
| 55 |
// predict with k nearest neighbors |
| 56 |
knn.predict( query, k, prob ); |
| 57 |
// print |
| 58 |
chout <= "query=(" + query[0] + "," + query[1] + "); k=" + k + ":" <= IO.newline(); |
| 59 |
for( 0 => int i; i < 3; i++ ) |
| 60 |
{ |
| 61 |
chout <= labelNames[i] + ": " + prob[i] <= IO.newline(); |
| 62 |
} |
| 63 |
chout <= IO.newline(); |
| 64 |
} |