Simvik

Normalise and classify

Normalise features with training statistics, then pick the nearest class centroid. A medium embedded C problem (Features for TinyML), run and graded in the…

medium · Features for TinyML · tinyml · features · classification

A classifier only works if the device computes features exactly as training did. Here three features (in their raw units) are normalised with the training mean and standard deviation, z = (x − mean) / std, and the window is labelled with the class whose centroid (in normalised units) is nearest by squared distance.

All values are integers scaled by 1000 (milli-units): z_milli = (x − mean) × 1000 / std, rounded toward zero.

Write classify(x, mean, std, centroids, n_classes): normalise the 3 features, find the nearest centroid (the lowest index on ties), and return its index. Use 64-bit integers for the squared distances.

Starter code

int classify(const int32_t *x, const int32_t *mean, const int32_t *std, const int32_t (*centroids)[3], int n_classes) {
  (void)mean; (void)std;
  int best = 0;
  int64_t best_d = -1;
  for (int c = 0; c < n_classes; c++) {
    int64_t d = 0;
    for (int k = 0; k < 3; k++) { int64_t e = x[k] - centroids[c][k]; d += e * e; }
    if (best_d < 0 || d < best_d) { best_d = d; best = c; }
  }
  return best;
}

Example tests

A healthy machine

show(700, 5, 40000);

Expected output:

rms 700, e180 5, temp 40000: healthy

A bearing fault

show(820, 360, 42000);

Expected output:

rms 820, e180 360, temp 42000: bearing fault

Learn it first

  • Features for TinyML · Windows, RMS and band energy, Goertzel, normalisation and a nearest-centroid classifier.