Skip to content

Instantly share code, notes, and snippets.

@eloquentarduino
Created February 9, 2020 18:26
Show Gist options
  • Save eloquentarduino/75359a8305e05023882c1fccff335abd to your computer and use it in GitHub Desktop.
Save eloquentarduino/75359a8305e05023882c1fccff335abd to your computer and use it in GitHub Desktop.
Even smaller IRIS classification for microcontrollers
/**
* Do dot product between vectors
*/
double compute_kernel(double x[3], ...) {
va_list w;
double kernel = 0.0;
va_start(w, 3);
for (uint16_t i = 0; i < 3; i++)
kernel += x[i] * va_arg(w, double) ;
return kernel;
}
/**
* Predict class from features
*/
uint8_t predict(double *x) {
double decision[3] = {0};
decision[0] = (compute_kernel(x, 7.7, 2.6, 6.9, 2.3) - 81.63139999999996 ) * -0.294744878436046 - 3.616434571769916;
decision[1] = -0.6931764919596977;
decision[2] = (compute_kernel(x, 6.3, 3.3, 6.0, 2.5) - 72.44853333333332 ) * 0.2380608846577031 - 2.3493312085177753;
uint8_t idx = 0;
double val = decision[0];
for (uint8_t i = 1; i < 3; i++) {
if (decision[i] > val) {
idx = i;
val = decision[i];
}
}
return idx;
}
/**
* Get accuracy on test set
*/
void self_test() {
int correct = 0;
double X[10][4] = {
{ 5.5 , 4.2 , 1.4 , 0.2 }
, { 5.1 , 3.8 , 1.6 , 0.2 }
, { 5.5 , 2.6 , 4.4 , 1.2 }
, { 6.6 , 2.9 , 4.6 , 1.3 }
, { 6.3 , 2.8 , 5.1 , 1.5 }
, { 6.1 , 2.6 , 5.6 , 1.4 }
, { 7.6 , 3 , 6.6 , 2.1 }
, { 6.3 , 2.7 , 4.9 , 1.8 }
, { 4.5 , 2.3 , 1.3 , 0.3 }
, { 6.3 , 2.3 , 4.4 , 1.3 }
};
int y[10] = { 0, 0, 1, 1, 2, 2, 2, 2, 0, 1 };
for (int i = 0; i < 10; i++) {
int predicted = predict(X[i]);
Serial.print('#');
Serial.print(i);
Serial.print("\t Expected ");
Serial.print(y[i]);
Serial.print("\tGot ");
Serial.print(predicted);
Serial.print('\t');
Serial.print(predicted == y[i] ? "OK\n" : "ERR\n");
correct += (predicted == y[i]) ? 1 : 0;
}
Serial.print("Run 10 predictions. ");
Serial.print(correct);
Serial.print(" were OK (");
Serial.print(100 * correct / 10);
Serial.print("%)");
}
void setup() {
Serial.begin(115200);
delay(3000);
self_test();
}
void loop() {}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment