Implement your Bayesian estimator with CMSIS-DSP

Once the parameters of the Bayesian classifier have been dumped from the Python code, you can use them in your C code with the CMSIS-DSP.

You can find the full code in CMSIS/DSP/Examples/ARM/arm_bayes_example/arm_bayes_example_f32.c

This example reproduces the Python prediction by using the same test points.

The following code declares the instance variable that is used by the Bayesian classifier and some lengths.

This instance variable contains all the parameters which have been dumped from Python.

Some of those parameters are arrays. This means that we must specify their sizes, using the number of classes and the vector dimensions:

arm_gaussian_naive_bayes_instance_f32 S;

#define NB_OF_CLASSES 3
#define VECTOR_DIMENSION 2

Three arrays of parameters are required:

  • Gaussian averages (theta)
  • Gaussian variances (sigma)
  • The class prior probabilities

The following code defines the content of the arrays. The values are dumped from Python:

const float32_t theta[NB_OF_CLASSES*VECTOR_DIMENSION] = {
  1.4539529436590528f, 0.8722776016801852f, 
  -1.5267934452462473f, 0.903204577814203f, 
  -0.15338006360932258f, -2.9997913665803964f
}; /**< Mean values for the Gaussians */

const float32_t sigma[NB_OF_CLASSES*VECTOR_DIMENSION] = {
  1.0063470889514925f, 0.9038018246524426f, 
  1.0224479953244736f, 0.7768764290432544f, 
  1.1217662403241206f, 1.2303890106020325f
}; /**< Variances for the Gaussians */

const float32_t classPriors[NB_OF_CLASSES] = {
  0.3333333333333333f, 0.3333333333333333f, 0.3333333333333333f
}; /**< Class prior probabilities */

The following code fills the instance variable fields with the arrays, some sizes, and the epsilon value coming from Python.

S.vectorDimension = VECTOR_DIMENSION; 
S.numberOfClasses = NB_OF_CLASSES; 
S.theta = theta;          
S.sigma = sigma;         
S.classPriors = classPriors;    
S.epsilon=4.328939296523643e-09;

Once the data structure is initialized, it is possible to use the classifier. The classifier estimates the probability of each class. However, this classifier is not a good estimator. This means that the values of the probabilities should not be used, except to find the max probability which gives the most likely class for the sample.

The following code tests the classifier on a sample point that is inside cluster A corresponding to class 0.

To find the class, the code looks for the maximum probability, which is giving the most likely class.

in[0] = 1.5f;
in[1] = 1.0f;

arm_gaussian_naive_bayes_predict_f32(&S, in, result);

arm_max_f32(result,
        NB_OF_CLASSES,
        &maxProba,
        &index);

printf("Class = %d\n",index);
Previous Next