-
Notifications
You must be signed in to change notification settings - Fork 0
/
Perceptron.pde
60 lines (57 loc) · 1.04 KB
/
Perceptron.pde
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
//The Activation Function
int sign(float n)
{
if (n >= 0)
{
return 1;
}
else
{
return -1;
}
}
class Perceptron
{
float [] weights;
float lr = 0.01;
//Constructor
Perceptron(int n)
{
weights = new float[n];
//Intialize the weights randomly
for (int i = 0; i < weights.length; i++)
{
weights[i] = random(-1, 1);
}
}
int guess(float[] inputs)
{
float sum = 0;
for(int i = 0; i < weights.length; i++)
{
sum += inputs[i] * weights[i];
}
int output = sign(sum);
return output;
}
void train(float[] inputs, int target)
{
int guess = guess(inputs);
int error = target - guess;
//Tune all the weights
for (int i = 0; i < weights.length; i++)
{
weights[i] += error * inputs[i] * lr;
}
}
float guessY(float x)
{
//float m = weights[1] / weights [0];
//float b = weights[2];
//return m * x + b;
float w0 = weights[0];
float w1 = weights[1];
float w2 = weights[2];
return -(w2/w1) - (w0/w1) * x;
}
}