-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathNeuron.cpp
73 lines (60 loc) · 1.91 KB
/
Neuron.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
#include "Neuron.h"
#include "NeuralNetwork.h"
#include <algorithm>
#include <iostream>
Neuron::Neuron(int new_neuron_index, int output_num) : this_neuron_index(new_neuron_index), value(0.0), gradient(0.0)
{
this->output_weights.assign(output_num, Connection());
}
void Neuron::SetValue(double new_value)
{
this->value = new_value;
}
double Neuron::GetValue() const
{
return this->value;
}
void Neuron::FeedForwardFrom(const Layer& previous_layer)
{
this->value = 0.0;
for (const Neuron& prev_neuron : previous_layer)
{
this->value += prev_neuron.value * prev_neuron.output_weights[this->this_neuron_index].weight;
}
this->value = Neuron::TransferFunction(this->value);
}
void Neuron::UpdateOutputLayerGradient(double target_value)
{
double loss = target_value - this->value;
this->gradient = loss * Neuron::TransferFunctionDerv(this->value);
}
void Neuron::UpdateHiddenLayerGradient(const Layer& next_layer)
{
//sum of derivative of weight
double sum_DOW = 0.0;
for (int neuron_index = 0; neuron_index < next_layer.size() - 1; ++neuron_index)
{
sum_DOW += this->output_weights[neuron_index].weight * next_layer[neuron_index].gradient;
}
this->gradient = sum_DOW * Neuron::TransferFunctionDerv(this->value);
}
void Neuron::UpdateLayerWeight(Layer& prev_layer)
{
for (Neuron& prev_neuron : prev_layer)
{
double old_diff_weight = prev_neuron.output_weights[this->this_neuron_index].diff_weight;
double new_diff_weight = prev_neuron.value * this->gradient * LEARNING_RATE + old_diff_weight * MOMENTUM_RATE;
prev_neuron.output_weights[this->this_neuron_index].diff_weight = new_diff_weight;
prev_neuron.output_weights[this->this_neuron_index].weight += new_diff_weight;
}
}
double Neuron::TransferFunction(double value)
{
//sigmoid 1.0 / (1.0 - std::exp(-value))
return tanh(value);
}
double Neuron::TransferFunctionDerv(double value)
{
double tanh_value = tanh(value);
return 1.0 - tanh_value * tanh_value;
}