-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathneuron.cpp
More file actions
82 lines (67 loc) · 1.99 KB
/
Copy pathneuron.cpp
File metadata and controls
82 lines (67 loc) · 1.99 KB
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
#include "neuron.hpp"
Neuron::Neuron(unsigned int numOutputs, unsigned int index)
{
for(unsigned int i = 0; i < numOutputs; i++)
{
outputWeights.push_back(Connection());
outputWeights.back().weight = randomWeight();
}
this->index = index;
}
void Neuron::feedForward(Layer &prevLayer)
{
double sum = 0.0;
for(unsigned int i = 0; i < prevLayer.size(); i++)
{
sum += prevLayer[i].getOutputVal() *
prevLayer[i].outputWeights[index].weight;
}
outputVal = activationFunction(sum);
}
double Neuron::activationFunction(double x)
{
return tanh(x);
}
double Neuron::activationFunctionDerivative(double x)
{
return 1.0 - x * x;
}
void Neuron::calcOutputGradients(double targetVal)
{
double delta = targetVal - outputVal;
gradient = delta * activationFunction(outputVal);
}
void Neuron::calcHiddenGradients(Layer &nextLayer)
{
double dow = sumDOW(nextLayer);
gradient = dow * activationFunction(outputVal);
}
double Neuron::sumDOW(Layer &nextLayer)
{
double sum = 0.0;
for(unsigned int n = 0; n < nextLayer.size() - 1; n++)
{
sum += outputWeights[n].weight * nextLayer[n].gradient;
}
return sum;
}
void Neuron::updateInputWeights(Layer &prevLayer)
{
// The weights to be updated are in the Connection container
// in the neurons in the preceding layer
for(unsigned int n = 0; n < prevLayer.size(); n++)
{
Neuron &neuron = prevLayer[n];
double oldDeltaWeight = neuron.outputWeights[index].deltaWeight;
double newDeltaWeight =
// Individual input, magnified by the gradient and train rate
eta
* neuron.getOutputVal()
* gradient
// Also add momentum = a fraction of the previous delta weight
+ alpha
* oldDeltaWeight;
neuron.outputWeights[index].deltaWeight = newDeltaWeight;
neuron.outputWeights[index].weight += newDeltaWeight;
}
}