-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclassification.cpp
95 lines (84 loc) · 2.76 KB
/
classification.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
//
// regression2.cpp
//
// purpose: make prediction of sensor color based on binary sensor
// input and input Beta Coefficients
// By: Ashton Stephens
// Date: 3/8/18
//
/* THE PROBLEM:
*
* The sensors used on this bot are purely brightness sensors. We
* can read in a single analog value between 0-1024 and that's it.
* using only those kinds of readings our bot needs to isolate which
* of the following colors it is currently "looking at":
*
* RED, BLUE, YELLOW, BLACK
*
* In order to determine which color of paper the robot is looking,
* it flashes red and blue lights at the surface of the paper and
* uses those readings to figure out the red and blue components of
* the paper.
*
* WHY MACHINE LEARNING?:
*
* Because the sensors used on this bot vary a lot between devices,
* the code needs to determine per sensor, how much the sensor values
* at different states of the blue and red light flashing actually
* show the red and blue components of the paper. To compensate for
* the variability in the sensors, we use a logistic machine learning
* algorithm to decide whether there is a strong red component and
* strong blue component for each period of the red and blue lights
* flashing. Because we iterate over 2 states of the blue and red
* lights on we have four readings that allow us to determine what
* color we're on.
*
* (just red on -> both on -> just blue on -> both off -> ...)
*
* NOTE: the Beta values are derived using a separate piece of code
* that does not run while the bot is running. The Beta values are
* generated using a simple logistic regression algorithm.
*
*/
#include "classification.h"
/* perform classification based on sensor values X and Beta values B */
float hypothesis (const float X[NPARAMS], const float B[NPARAMS+1])
{
float sum = B[0];
for (int i = 0; i < NPARAMS; ++i) {
sum += B[i+1] * X[i];
}
return sum;
}
float logistic (const float X[NPARAMS], const float B[NPARAMS+1])
{
return ((float)1.0) / (1 + exp(-hypothesis(X,B)));
}
bool predict_component(const float X[NPARAMS], const float B[NPARAMS+1])
{
float temp = logistic(X,B);
return temp >= 0.5;
}
/* make a prediction of what color we're on based on each esimated color */
color predict(bool red, bool blue)
{
if (red) {
if (blue) {
return YELLOW;
} else {
return RED;
}
} else {
if (blue) {
return BLUE;
} else {
return BLACK;
}
}
}
/* predict the full color the sensor is on */
color predict_full (const float X[NPARAMS], const float redB[NPARAMS+1],
const float bluB[NPARAMS+1])
{
return predict(predict_component(X,redB), predict_component(X,bluB));
}