-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathneuralNetADS.cpp
More file actions
412 lines (330 loc) · 10.2 KB
/
Copy pathneuralNetADS.cpp
File metadata and controls
412 lines (330 loc) · 10.2 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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
// Author: Alden Sahi
// Date: Oct 2024
// Project Name: NeuralNetADS
// Project Description: Implementing an Implicitly and Fully Connected Neural Network using CPP
#include <vector>
#include <cstdlib>
#include <iostream>
#include <cassert>
#include <cmath>
#include <sstream>
#include <fstream>
using namespace std;
struct Connection
{
double weight;
double deltaWeight;
};
class Neuron;
typedef vector<Neuron> Layer;
/*------------------ NEURON CLASS ----------------*/
class Neuron
{
public:
Neuron(unsigned numOutputs, unsigned myIndex);
void setOutputVal(double val) { m_outputVal = val; }
double getOutputVal(void) const { return m_outputVal; }
void feedForward(const Layer &prevLayer);
void calcOutputGradients(double targetVal);
void calcHiddenGradients(const Layer &nextLayer);
void updateInputWeights(Layer &prevLayer);
private:
vector<Connection> m_outputWeights;
double m_outputVal;
unsigned m_myIndex;
double m_gradient;
static double eta; // learning rate
static double alpha; // momentum
static double activationFunction(double x) { return tanh(x); }
static double activationFunctionDerivative(double x);
static double randomWeight(void) { return rand() / double(RAND_MAX); }
double sumDOW(const Layer &nextLayer) const;
};
// initalize eta / alpha
double Neuron::eta = 0.15;
double Neuron::alpha = 0.5;
/*-------------- External Neuron Constructor Definition-----------------*/
Neuron::Neuron(unsigned numOutputs, unsigned myIndex)
{
/* Constructor Summary:
Iterates through all o
*/
for (unsigned i = 0; i < numOutputs; ++i)
{
m_outputWeights.push_back(Connection());
m_outputWeights.back().weight = randomWeight();
}
m_myIndex = myIndex;
};
/*-------------- Member Functions of Neuron -----------------*/
void Neuron::feedForward(const Layer &prevLayer)
{
/* Member Function Summary:
Sums the previous layers outputs with their corresponding weights
including the bias node
Params: A reference to the previos layer(in order to get their output value)
*/
double sum = 0.0;
for (int n = 0; n < prevLayer.size(); ++n)
{
sum += prevLayer[n].getOutputVal() * prevLayer[n].m_outputWeights[m_myIndex].weight;
}
m_outputVal = Neuron::activationFunction(sum);
}
double Neuron::activationFunctionDerivative(double x)
{
// derivative of tanh activation function specified in contructor
return 1.0 - (x * x);
}
void Neuron::calcOutputGradients(double targetVal)
{
double delta = targetVal - m_outputVal;
m_gradient = delta * Neuron::activationFunctionDerivative(m_outputVal);
}
void Neuron::calcHiddenGradients(const Layer &nextLayer)
{
double dow = sumDOW(nextLayer);
m_gradient = dow * Neuron::activationFunctionDerivative(m_outputVal);
}
double Neuron::sumDOW(const Layer &nextLayer) const
{
double sum = 0.0;
// sum total error given to inputs of next layer
for (unsigned n = 0; n < nextLayer.size() - 1; ++n)
{
sum += m_outputWeights[n].weight * nextLayer[n].m_gradient;
}
return sum;
}
void Neuron::updateInputWeights(Layer &prevLayer)
{
for (unsigned n = 0; n < prevLayer.size(); ++n)
{
Neuron &neuron = prevLayer[n];
double oldDeltaWeight = neuron.m_outputWeights[m_myIndex].deltaWeight;
double newDeltaWeight =
eta * // learning rate
neuron.getOutputVal() * m_gradient * alpha * oldDeltaWeight;
}
}
/*-------------------Network Class------------*/
class Network
{
public:
Network(const vector<unsigned> &topology);
void feedForward(const vector<double> &inputVals);
void backProp(const vector<double> &targetVals);
void getResults(vector<double> &resultsVals) const;
double getRecentAverageError(void) const { return m_recentAverageError; }
private:
// m_layers[layerNum][NeuronNum]
vector<Layer> m_layers;
double m_error;
double m_recentAverageError;
double m_recentAverageSmoothingFactor;
};
/*-------------- External Network Constructor Definition-----------------*/
Network::Network(const vector<unsigned> &topology)
{
/* Network Constructor Summary:
Populates m_layers with a number of layers corresponding to entries in topology
For each entry it will creat neurons based on user specified unsigned int
*/
unsigned numLayers = topology.size();
for (unsigned layerNum = 0; layerNum < numLayers; ++layerNum)
{
m_layers.push_back(Layer());
unsigned numOutputs = layerNum == topology.size() - 1 ? 0 : topology[layerNum + 1];
for (unsigned neuronNum = 0; neuronNum <= topology[layerNum]; ++neuronNum)
{
m_layers.back().push_back(Neuron(numOutputs, neuronNum));
}
m_layers.back().back().setOutputVal(1.0);
}
}
/*---------------- NETWORK MEMBER FUNCTIONS-------------------*/
void Network::feedForward(const vector<double> &inputVals)
{
assert(inputVals.size() == m_layers[0].size() - 1);
// latch inputVals to input neurons
for (int i = 0; i < inputVals.size(); ++i)
{
m_layers[0][i].setOutputVal(inputVals[i]);
}
// forward propogate (FOR ALL OTHER LAYERS)
for (unsigned layerNum = 1; layerNum < m_layers.size(); ++layerNum)
{
Layer &prevLayer = m_layers[layerNum - 1];
// for each neuron
for (unsigned n = 0; n < m_layers[layerNum].size() - 1; ++n)
{
// connect neuron to input vals of next layer
m_layers[layerNum][n].feedForward(prevLayer);
}
}
}
void Network::backProp(const vector<double> &targetVals)
{
// Calculate Root Mean Square Error of output neuron errors
Layer &outputLayer = m_layers.back();
m_error = 0.0;
for (unsigned n = 0; n < outputLayer.size() - 1; ++n)
{
double delta = targetVals[n] - outputLayer[n].getOutputVal();
m_error += delta * delta;
m_error = sqrt(m_error);
}
// calculates recent average
m_recentAverageError =
(m_recentAverageError * m_recentAverageSmoothingFactor + m_error) / (m_recentAverageSmoothingFactor + 1.0);
// calculates output layer gradient
for (unsigned n = 0; n < outputLayer.size() - 1; ++n)
{
outputLayer[n].calcOutputGradients(targetVals[n]);
}
// calculates gradients of hidden layer(s)
for (unsigned l = m_layers.size() - 2; l > 0; --l)
{
Layer &hiddenLayer = m_layers[l];
Layer &nextLayer = m_layers[l + 1];
for (unsigned n = 0; n < hiddenLayer.size(); ++n)
{
hiddenLayer[n].calcHiddenGradients(nextLayer);
}
}
// for all layers from outputs to first hidden layer,
// update connect weight
for (unsigned l = m_layers.size() - 1; l > 0; --l)
{
Layer &layer = m_layers[l];
Layer &prevLayer = m_layers[l - 1];
for (unsigned n = 0; n < m_layers[l].size() - 1; ++n)
{
layer[n].updateInputWeights(prevLayer);
}
}
}
void Network::getResults(vector<double> &resultsVals) const
{
resultsVals.clear();
for (unsigned n = 0; n < m_layers.back().size() - 1; ++n)
{
resultsVals.push_back(m_layers.back()[n].getOutputVal());
}
}
void showVectorVals(string label, vector<double> &v)
{
cout << label << " ";
for (unsigned i = 0; i < v.size(); ++i)
{
cout << v[i] << " ";
}
cout << endl;
}
/*------------- TrainingData Class ------------------*/
class TrainingData
{
public:
TrainingData(const string filename);
bool isEof(void) { return m_trainingDataFile.eof(); }
void getTopology(vector<unsigned> &topology);
unsigned getNextInputs(vector<double> &inputsVals);
unsigned getTargetOutputs(vector<double> &targetOutputVals);
private:
ifstream m_trainingDataFile;
};
void TrainingData::getTopology(vector<unsigned> &topology)
{
string line;
string label;
if (!getline(m_trainingDataFile, line))
{
cout << "Failed to read from file." << endl;
abort();
}
stringstream ss(line);
ss >> label;
if (this->isEof() || label.compare("topology:") != 0)
{
cout << "Expected 'topology:' but found: " << label << endl; abort();
}
while (!ss.eof())
{
unsigned n;
ss >> n;
topology.push_back(n);
}
return;
}
TrainingData::TrainingData(const string filename)
{
m_trainingDataFile.open(filename.c_str());
}
unsigned TrainingData::getNextInputs(vector<double> &inputVals)
{
inputVals.clear();
string line;
getline(m_trainingDataFile, line);
stringstream ss(line);
string label;
ss >> label;
if (label.compare("in:") == 0)
{
double oneValue;
while (ss >> oneValue)
{
inputVals.push_back(oneValue);
}
}
return inputVals.size();
}
unsigned TrainingData::getTargetOutputs(vector<double> &targetOutputVals)
{
targetOutputVals.clear();
string line;
getline(m_trainingDataFile, line);
stringstream ss(line);
string label;
ss >> label;
if (label.compare("out:") == 0)
{
double oneValue;
while (ss >> oneValue)
{
targetOutputVals.push_back(oneValue);
}
}
return targetOutputVals.size();
}
int main()
{
// creates Training Data
TrainingData trainData("TrainData.txt");
vector<unsigned> topology;
trainData.getTopology(topology);
Network myNetwork(topology);
vector<double> inputVals, targetVals, resultVals;
int trainingPass = 0;
while (!trainData.isEof())
{
++trainingPass;
cout << endl
<< "Pass " << trainingPass;
if (trainData.getNextInputs(inputVals) != topology[0])
{
break;
}
showVectorVals(": Inputs:", inputVals);
myNetwork.feedForward(inputVals);
myNetwork.getResults(resultVals);
showVectorVals("Outputs:", resultVals);
trainData.getTargetOutputs(targetVals);
showVectorVals("Targets:", targetVals);
assert(targetVals.size() == topology.back());
myNetwork.backProp(targetVals);
cout << "Net recent average error: "
<< myNetwork.getRecentAverageError() << endl;
}
cout << endl
<< "SUCCESS!";
}