-
Notifications
You must be signed in to change notification settings - Fork 0
/
neuron.cc
68 lines (60 loc) · 1.47 KB
/
neuron.cc
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
#ifndef NEURON_CC
#define NEURON_CC
#include <vector>
#include "value.cc"
#include "parameter.cc"
#include "random.cc"
class Neuron : BaseParameterClass
{
private:
bool linear = true;
public:
std::vector<ValuePtr> params;
Neuron(size_t n_inputs)
{
params = std::vector<ValuePtr>();
std::generate_n(std::back_inserter(params), n_inputs + 1, []
{ return ValuePtr(new Value{get_next_random_weight()}); });
for (const auto param : params)
{
param->needs_grad = true;
}
}
ValuePtr run(std::vector<ValuePtr> inputs)
{
// adding one term for the bias
inputs.push_back(ValuePtr(new Value(1)));
if (inputs.size() != params.size())
{
std::cerr << "can't process inputs that don't match number of weights" << std::endl;
}
auto act = ValuePtr(new Value(0.0));
for (auto index = 0; index < inputs.size(); index++)
{
act = act->add(params[index]->mul(inputs[index]));
}
if (!linear)
{
return act->relu();
}
else
{
return act;
}
}
void zero_grad() override
{
for (auto param : this->params)
{
param->grad = 0;
}
}
void update_params(double alpha) override
{
for (auto param : this->params)
{
param->value -= param->grad * alpha;
}
}
};
#endif