-
Notifications
You must be signed in to change notification settings - Fork 0
/
Perceptron.cpp
60 lines (55 loc) · 2.05 KB
/
Perceptron.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
#include "Perceptron.h"
/* Helper's prototypes */
double frand();
double precision(double num, int n);
/***************************************************************************************
Constructors | Getters | Setters
****************************************************************************************/
/**
* @inputs: number of input of our perceptron;
* @bias: bias of the perceptron;
* @return a new Perceptron obj with inputs + 1 (for the bias) inputs;
*/
Perceptron::Perceptron(int inputs, double bias) {
this->bias = bias;
this->weights.resize(inputs + 1);
generate(weights.begin(), weights.end(), frand);
}
vector<double> Perceptron::get_weights() {
return this->weights;
}
void Perceptron::set_weights(vector<double> w_init) {
this->weights = w_init;
}
void Perceptron::incr_weight(int index, double delta) {
this->weights[index] += delta;
}
/***************************************************************************************
Helpers
****************************************************************************************/
/**
* @return a random value between -1 and 1;
*/
double frand() {
double time2 = 2.0 * (double)rand() / RAND_MAX; // time2 belongs to [0, 2]
return time2 - 1.0; // belongs to [-1, 1]
}
/* Precision of @n digit after the dot */
double precision(double num, int n) {
double value = (int)(num * pow(10, n));
return (double)value / pow(10, n);
}
/***************************************************************************************
Methods
****************************************************************************************/
double Perceptron::predict(vector<double> x) {
x.push_back(this->bias);
double z = inner_product(x.begin(), x.end(), this->weights.begin(), 0.0);
return sigmoid(z);
}
double Perceptron::sigmoid(double x) {
// double s = 1.0 / (1.0 + exp(-x));
// cout << "sigmoid(" << x << ") == " << s << endl;
// return s;
return 1.0 / (1.0 + exp(-x));
}