n2p2 - A neural network potential package
NeuralNetwork.cpp
Go to the documentation of this file.
1// n2p2 - A neural network potential package
2// Copyright (C) 2018 Andreas Singraber (University of Vienna)
3//
4// This program is free software: you can redistribute it and/or modify
5// it under the terms of the GNU General Public License as published by
6// the Free Software Foundation, either version 3 of the License, or
7// (at your option) any later version.
8//
9// This program is distributed in the hope that it will be useful,
10// but WITHOUT ANY WARRANTY; without even the implied warranty of
11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12// GNU General Public License for more details.
13//
14// You should have received a copy of the GNU General Public License
15// along with this program. If not, see <https://www.gnu.org/licenses/>.
16
17#include "NeuralNetwork.h"
18#include "utility.h"
19#include <algorithm> // std::min, std::max
20#include <cmath> // sqrt, pow, tanh
21#include <cstdio> // fprintf, stderr
22#include <cstdlib> // exit, EXIT_FAILURE, rand, srand
23#include <limits> // std::numeric_limits
24
25#define EXP_LIMIT 35.0
26
27using namespace std;
28using namespace nnp;
29
30NeuralNetwork::
31NeuralNetwork(int numLayers,
32 int const* const& numNeuronsPerLayer,
33 ActivationFunction const* const& activationFunctionsPerLayer)
34{
35 // check number of layers
36 this->numLayers = numLayers;
37 if (numLayers < 3)
38 {
39 fprintf(stderr,
40 "ERROR: Neural network must have at least three layers\n");
41 exit(EXIT_FAILURE);
42 }
44
45 // do not normalize neurons by default
46 normalizeNeurons = false;
47
48 // allocate layers and populate with neurons
49 layers = new Layer[numLayers];
50 inputLayer = &layers[0];
53 0,
54 numNeuronsPerLayer[0],
55 activationFunctionsPerLayer[0]);
56 for (int i = 1; i < numLayers; i++)
57 {
59 numNeuronsPerLayer[i-1],
60 numNeuronsPerLayer[i],
61 activationFunctionsPerLayer[i]);
62 }
63
64 // count connections
65 numWeights = 0;
66 numBiases = 0;
68 for (int i = 1; i < numLayers; i++)
69 {
72 }
74
75 // calculate weight and bias offsets for each layer
76 weightOffset = new int[numLayers-1];
77 weightOffset[0] = 0;
78 for (int i = 1; i < numLayers-1; i++)
79 {
80 weightOffset[i] = weightOffset[i-1] +
81 (layers[i-1].numNeurons + 1) * layers[i].numNeurons;
82 }
83 biasOffset = new int[numLayers-1];
84 for (int i = 0; i < numLayers-1; i++)
85 {
86 biasOffset[i] = weightOffset[i] +
88 }
89 biasOnlyOffset = new int[numLayers-1];
90 biasOnlyOffset[0] = 0;
91 for (int i = 1; i < numLayers-1; i++)
92 {
94 }
95}
96
98{
99 for (int i = 0; i < numLayers; i++)
100 {
101 for (int j = 0; j < layers[i].numNeurons; j++)
102 {
103 delete[] layers[i].neurons[j].weights;
104 }
105 delete[] layers[i].neurons;
106 }
107 delete[] layers;
108 delete[] weightOffset;
109 delete[] biasOffset;
110 delete[] biasOnlyOffset;
111}
112
113void NeuralNetwork::setNormalizeNeurons(bool normalizeNeurons)
114{
115 this->normalizeNeurons = normalizeNeurons;
116
117 return;
118}
119
121{
122 int count = 0;
123
124 for (int i = 0; i < numLayers; i++)
125 {
126 count += layers[i].numNeurons;
127 }
128
129 return count;
130}
131
133{
134 return numConnections;
135}
136
138{
139 return numWeights;
140}
141
143{
144 return numBiases;
145}
146
147void NeuralNetwork::setConnections(double const* const& connections)
148{
149 int count = 0;
150
151 for (int i = 1; i < numLayers; i++)
152 {
153 for (int j = 0; j < layers[i].numNeuronsPrevLayer; j++)
154 {
155 for (int k = 0; k < layers[i].numNeurons; k++)
156 {
157 layers[i].neurons[k].weights[j] = connections[count];
158 count++;
159 }
160 }
161 for (int j = 0; j < layers[i].numNeurons; j++)
162 {
163 layers[i].neurons[j].bias = connections[count];
164 count++;
165 }
166 }
167
168 return;
169}
170
171void NeuralNetwork::getConnections(double* connections) const
172{
173 int count = 0;
174
175 for (int i = 1; i < numLayers; i++)
176 {
177 for (int j = 0; j < layers[i].numNeuronsPrevLayer; j++)
178 {
179 for (int k = 0; k < layers[i].numNeurons; k++)
180 {
181 connections[count] = layers[i].neurons[k].weights[j] ;
182 count++;
183 }
184 }
185 for (int j = 0; j < layers[i].numNeurons; j++)
186 {
187 connections[count] = layers[i].neurons[j].bias;
188 count++;
189 }
190 }
191
192 return;
193}
194
196{
197 double* connections = new double[numConnections];
198
199 srand(seed);
200 for (int i = 0; i < numConnections; i++)
201 {
202 connections[i] = -1.0 + 2.0 * (double)rand() / RAND_MAX;
203 }
204
205 setConnections(connections);
206
207 delete[] connections;
208
209 return;
210}
211
213{
214 if (modificationScheme == MS_ZEROBIAS)
215 {
216 for (int i = 0; i < numLayers; i++)
217 {
218 for (int j = 0; j < layers[i].numNeurons; j++)
219 {
220 layers[i].neurons[j].bias = 0.0;
221 }
222 }
223 }
224 else if (modificationScheme == MS_ZEROOUTPUTWEIGHTS)
225 {
226 for (int i = 0; i < outputLayer->numNeurons; i++)
227 {
228 for (int j = 0; j < outputLayer->numNeuronsPrevLayer; j++)
229 {
230 outputLayer->neurons[i].weights[j] = 0.0;
231 }
232 }
233 }
234 else if (modificationScheme == MS_FANIN)
235 {
236 for (int i = 1; i < numLayers; i++)
237 {
238 if(layers[i].activationFunction == AF_TANH)
239 {
240 for (int j = 0; j < layers[i].numNeurons; j++)
241 {
242 for (int k = 0; k < layers[i].numNeuronsPrevLayer; k++)
243 {
244 layers[i].neurons[j].weights[k] /=
245 sqrt(layers[i].numNeuronsPrevLayer);
246 }
247 }
248 }
249 }
250 }
251 else if (modificationScheme == MS_GLOROTBENGIO)
252 {
253 for (int i = 1; i < numLayers; i++)
254 {
255 if(layers[i].activationFunction == AF_TANH)
256 {
257 for (int j = 0; j < layers[i].numNeurons; j++)
258 {
259 for (int k = 0; k < layers[i].numNeuronsPrevLayer; k++)
260 {
261 layers[i].neurons[j].weights[k] *= sqrt(6.0 / (
262 layers[i].numNeuronsPrevLayer
263 + layers[i].numNeurons));
264 }
265 }
266 }
267 }
268 }
269 else if (modificationScheme == MS_NGUYENWIDROW)
270 {
271 double beta = 0.0;
272 double sum = 0.0;
273 double weight = 0.0;
274
275 for (int i = 1; i < numLayers-1; i++)
276 {
277 beta = 0.7 * pow(layers[i].numNeurons,
278 1.0 / double(layers[i].numNeuronsPrevLayer));
279 for (int j = 0; j < layers[i].numNeurons; j++)
280 {
281 sum = 0.0;
282 for (int k = 0; k < layers[i].numNeuronsPrevLayer; k++)
283 {
284 weight = layers[i].neurons[j].weights[k];
285 sum += weight * weight;
286 }
287 sum = sqrt(sum);
288 for (int k = 0; k < layers[i].numNeuronsPrevLayer; k++)
289 {
290 layers[i].neurons[j].weights[k] *= beta / sum;
291 if (layers[i].activationFunction == AF_TANH)
292 {
293 layers[i].neurons[j].weights[k] *= 2.0;
294 }
295 }
296 layers[i].neurons[j].bias *= beta;
297 if (layers[i].activationFunction == AF_TANH)
298 {
299 layers[i].neurons[j].bias *= 2.0;
300 }
301 }
302 }
303 for (int i = 0; i < outputLayer->numNeurons; i++)
304 {
305 outputLayer->neurons[0].weights[i] *= 0.5;
306 }
307 }
308 else
309 {
310 fprintf(stderr, "ERROR: Incorrect modifyConnections call.\n");
311 exit(EXIT_FAILURE);
312 }
313
314 return;
315}
316
318 double parameter1,
319 double parameter2)
320{
321 if (modificationScheme == MS_PRECONDITIONOUTPUT)
322 {
323 double mean = parameter1;
324 double sigma = parameter2;
325
326 for (int i = 0; i < outputLayer->numNeurons; i++)
327 {
328 for (int j = 0; j < outputLayer->numNeuronsPrevLayer; j++)
329 {
330 outputLayer->neurons[i].weights[j] *= sigma;
331 }
332 outputLayer->neurons[i].bias += mean;
333 }
334 }
335 else
336 {
337 fprintf(stderr, "ERROR: Incorrect modifyConnections call.\n");
338 exit(EXIT_FAILURE);
339 }
340
341 return;
342}
343
344void NeuralNetwork::setInput(size_t const index, double const value) const
345{
346 Neuron& n = inputLayer->neurons[index];
347 n.count++;
348 n.value = value;
349 n.min = min(value, n.min);
350 n.max = max(value, n.max);
351 n.sum += value;
352 n.sum2 += value * value;
353
354 return;
355}
356
357void NeuralNetwork::setInput(double const* const& input) const
358{
359 for (int i = 0; i < inputLayer->numNeurons; i++)
360 {
361 // TODO: replace by calling setInput from above
362 // also, for 4G we need charges
363 double const& value = input[i];
364 Neuron& n = inputLayer->neurons[i];
365 n.count++;
366 n.value = value;
367 n.min = min(value, n.min);
368 n.max = max(value, n.max);
369 n.sum += value;
370 n.sum2 += value * value;
371 }
372
373 return;
374}
375
376void NeuralNetwork::getOutput(double* output) const
377{
378 for (int i = 0; i < outputLayer->numNeurons; i++)
379 {
380 output[i] = outputLayer->neurons[i].value;
381 }
382
383 return;
384}
385
387{
388 for (int i = 1; i < numLayers; i++)
389 {
390 propagateLayer(layers[i], layers[i-1]);
391 }
392
393 return;
394}
395
396void NeuralNetwork::calculateDEdG(double *dEdG) const
397{
398 double** inner = new double*[numHiddenLayers];
399 double** outer = new double*[numHiddenLayers];
400
401 for (int i = 0; i < numHiddenLayers; i++)
402 {
403 inner[i] = new double[layers[i+1].numNeurons];
404 outer[i] = new double[layers[i+2].numNeurons];
405 }
406
407 for (int k = 0; k < layers[0].numNeurons; k++)
408 {
409 for (int i = 0; i < layers[1].numNeurons; i++)
410 {
411 inner[0][i] = layers[1].neurons[i].weights[k]
412 * layers[1].neurons[i].dfdx;
413 if (normalizeNeurons) inner[0][i] /= layers[0].numNeurons;
414 }
415 for (int l = 1; l < numHiddenLayers+1; l++)
416 {
417 for (int i2 = 0; i2 < layers[l+1].numNeurons; i2++)
418 {
419 outer[l-1][i2] = 0.0;
420 for (int i1 = 0; i1 < layers[l].numNeurons; i1++)
421 {
422 outer[l-1][i2] += layers[l+1].neurons[i2].weights[i1]
423 * inner[l-1][i1];
424 }
425 outer[l-1][i2] *= layers[l+1].neurons[i2].dfdx;
426 if (normalizeNeurons) outer[l-1][i2] /= layers[l].numNeurons;
427 if (l < numHiddenLayers) inner[l][i2] = outer[l-1][i2];
428 }
429 }
430 dEdG[k] = outer[numHiddenLayers-1][0];
431 }
432
433 for (int i = 0; i < numHiddenLayers; i++)
434 {
435 delete[] inner[i];
436 delete[] outer[i];
437 }
438 delete[] inner;
439 delete[] outer;
440
441 return;
442}
443
444void NeuralNetwork::calculateDEdc(double* dEdc) const
445{
446 int count = 0;
447
448 for (int i = 0; i < numConnections; i++)
449 {
450 dEdc[i] = 0.0;
451 }
452
453 for (int i = 0; i < outputLayer->numNeurons; i++)
454 {
457 {
458 dEdc[biasOffset[numLayers-2]+i] /=
460 }
461 }
462
463 for (int i = numLayers-2; i >= 0; i--)
464 {
465 count = 0;
466 for (int j = 0; j < layers[i].numNeurons; j++)
467 {
468 for (int k = 0; k < layers[i+1].numNeurons; k++)
469 {
470 dEdc[weightOffset[i]+count] = dEdc[biasOffset[i]+k]
471 * layers[i].neurons[j].value;
472 count++;
473 if (i >= 1)
474 {
475 dEdc[biasOffset[i-1]+j] += dEdc[biasOffset[i]+k]
476 * layers[i+1].neurons[k].weights[j]
477 * layers[i].neurons[j].dfdx;
478 }
479 }
480 if (normalizeNeurons && i >= 1)
481 {
482 dEdc[biasOffset[i-1]+j] /= layers[i].numNeuronsPrevLayer;
483 }
484 }
485 }
486
487 return;
488}
489
491 double const* const& dGdxyz) const
492{
493 double* dEdb = new double[numBiases];
494 double* d2EdGdc = new double[numConnections];
495
496 for (int i = 0; i < numBiases; i++)
497 {
498 dEdb[i] = 0.0;
499 }
500 for (int i = 0; i < numConnections; i++)
501 {
502 dFdc[i] = 0.0;
503 d2EdGdc[i] = 0.0;
504 }
505
506 calculateDEdb(dEdb);
507 for (int i = 0; i < layers[0].numNeurons; i++)
508 {
509 for (int j = 0; j < numConnections; j++)
510 {
511 d2EdGdc[j] = 0.0;
512 }
513 calculateDxdG(i);
514 calculateD2EdGdc(i, dEdb, d2EdGdc);
515 for (int j = 0; j < numConnections; j++)
516 {
517 // Note: F = - dE / dx !!
518 // ^
519 dFdc[j] -= d2EdGdc[j] * dGdxyz[i];
520 }
521 }
522
523 delete[] dEdb;
524 delete[] d2EdGdc;
525
526 return;
527}
528
529void NeuralNetwork::writeConnections(std::ofstream& file) const
530{
531 // File header.
532 vector<string> title;
533 vector<string> colName;
534 vector<string> colInfo;
535 vector<size_t> colSize;
536 title.push_back("Neural network connection values (weights and biases).");
537 colSize.push_back(24);
538 colName.push_back("connection");
539 colInfo.push_back("Neural network connection value.");
540 colSize.push_back(1);
541 colName.push_back("t");
542 colInfo.push_back("Connection type (a = weight, b = bias).");
543 colSize.push_back(9);
544 colName.push_back("index");
545 colInfo.push_back("Index enumerating weights.");
546 colSize.push_back(5);
547 colName.push_back("l_s");
548 colInfo.push_back("Starting point layer (end point layer for biases).");
549 colSize.push_back(5);
550 colName.push_back("n_s");
551 colInfo.push_back("Starting point neuron in starting layer (end point "
552 "neuron for biases).");
553 colSize.push_back(5);
554 colName.push_back("l_e");
555 colInfo.push_back("End point layer.");
556 colSize.push_back(5);
557 colName.push_back("n_e");
558 colInfo.push_back("End point neuron in end layer.");
560 createFileHeader(title, colSize, colName, colInfo));
561
562 int count = 0;
563 for (int i = 1; i < numLayers; i++)
564 {
565 for (int j = 0; j < layers[i].numNeuronsPrevLayer; j++)
566 {
567 for (int k = 0; k < layers[i].numNeurons; k++)
568 {
569 count++;
570 file << strpr("%24.16E a %9d %5d %5d %5d %5d\n",
571 layers[i].neurons[k].weights[j],
572 count,
573 i - 1,
574 j + 1,
575 i,
576 k + 1);
577 }
578 }
579 for (int j = 0; j < layers[i].numNeurons; j++)
580 {
581 count++;
582 file << strpr("%24.16E b %9d %5d %5d\n",
583 layers[i].neurons[j].bias,
584 count,
585 i,
586 j + 1);
587 }
588 }
589
590 return;
591}
592
593void NeuralNetwork::calculateDEdb(double* dEdb) const
594{
595 for (int i = 0; i < outputLayer->numNeurons; i++)
596 {
599 {
600 dEdb[biasOnlyOffset[numLayers-2]+i] /=
602 }
603 }
604
605 for (int i = numLayers-2; i >= 0; i--)
606 {
607 for (int j = 0; j < layers[i].numNeurons; j++)
608 {
609 for (int k = 0; k < layers[i+1].numNeurons; k++)
610 {
611 if (i >= 1)
612 {
613 dEdb[biasOnlyOffset[i-1]+j] += dEdb[biasOnlyOffset[i]+k]
614 * layers[i+1].neurons[k].weights[j]
615 * layers[i].neurons[j].dfdx;
616 }
617 }
618 if (normalizeNeurons && i >= 1)
619 {
620 dEdb[biasOnlyOffset[i-1]+j] /= layers[i].numNeuronsPrevLayer;
621 }
622 }
623 }
624
625 return;
626}
627
628void NeuralNetwork::calculateDxdG(int index) const
629{
630 for (int i = 0; i < layers[1].numNeurons; i++)
631 {
632 layers[1].neurons[i].dxdG = layers[1].neurons[i].weights[index];
634 {
636 }
637 }
638 for (int i = 2; i < numLayers; i++)
639 {
640 for (int j = 0; j < layers[i].numNeurons; j++)
641 {
642 layers[i].neurons[j].dxdG = 0.0;
643 for (int k = 0; k < layers[i-1].numNeurons; k++)
644 {
645 layers[i].neurons[j].dxdG += layers[i].neurons[j].weights[k]
646 * layers[i-1].neurons[k].dfdx
647 * layers[i-1].neurons[k].dxdG;
648 }
650 {
652 }
653 }
654 }
655
656 return;
657}
658
660 double const* const& dEdb,
661 double* d2EdGdc) const
662{
663 int count = 0;
664
665 for (int i = 0; i < outputLayer->numNeurons; i++)
666 {
667 d2EdGdc[biasOffset[numLayers-2]+i] = outputLayer->neurons[i].d2fdx2
670 {
671 d2EdGdc[biasOffset[numLayers-2]+i] /=
673 }
674 }
675
676 for (int i = numLayers-2; i >= 0; i--)
677 {
678 count = 0;
679 for (int j = 0; j < layers[i].numNeurons; j++)
680 {
681 for (int k = 0; k < layers[i+1].numNeurons; k++)
682 {
683 if (i == 0)
684 {
685 d2EdGdc[weightOffset[i]+count] =
686 d2EdGdc[biasOffset[i]+k] * layers[i].neurons[j].value;
687 if (j == index)
688 {
689 d2EdGdc[weightOffset[i]+count] +=
690 dEdb[biasOnlyOffset[i]+k];
691 }
692 }
693 else
694 {
695 d2EdGdc[weightOffset[i]+count] =
696 d2EdGdc[biasOffset[i]+k] * layers[i].neurons[j].value
697 + dEdb[biasOnlyOffset[i]+k] * layers[i].neurons[j].dfdx
698 * layers[i].neurons[j].dxdG;
699 }
700 count++;
701 if (i >= 1)
702 {
703 d2EdGdc[biasOffset[i-1]+j] +=
704 layers[i+1].neurons[k].weights[j]
705 * (d2EdGdc[biasOffset[i]+k] * layers[i].neurons[j].dfdx
706 + dEdb[biasOnlyOffset[i]+k]
707 * layers[i].neurons[j].d2fdx2
708 * layers[i].neurons[j].dxdG);
709 }
710 }
711 if (normalizeNeurons && i >= 1)
712 {
713 d2EdGdc[biasOffset[i-1]+j] /= layers[i].numNeuronsPrevLayer;
714 }
715 }
716 }
717
718 return;
719}
720
722 int numNeuronsPrevLayer,
723 int numNeurons,
724 ActivationFunction activationFunction)
725{
726 layer.numNeurons = numNeurons;
727 layer.numNeuronsPrevLayer = numNeuronsPrevLayer;
728 layer.activationFunction = activationFunction;
729
730 layer.neurons = new Neuron[layer.numNeurons];
731 for (int i = 0; i < layer.numNeurons; i++)
732 {
733 layer.neurons[i].x = 0.0;
734 layer.neurons[i].value = 0.0;
735 layer.neurons[i].dfdx = 0.0;
736 layer.neurons[i].d2fdx2 = 0.0;
737 layer.neurons[i].bias = 0.0;
738 layer.neurons[i].dxdG = 0.0;
739 layer.neurons[i].count = 0;
740 layer.neurons[i].min = numeric_limits<double>::max();
741 layer.neurons[i].max = -numeric_limits<double>::max();
742 layer.neurons[i].sum = 0.0;
743 layer.neurons[i].sum2 = 0.0;
744 if (layer.numNeuronsPrevLayer > 0)
745 {
746 layer.neurons[i].weights = new double[layer.numNeuronsPrevLayer];
747 for (int j = 0; j < layer.numNeuronsPrevLayer; j++)
748 {
749 layer.neurons[i].weights[j] = 0.0;
750 }
751 }
752 else
753 {
754 layer.neurons[i].weights = 0;
755 }
756 }
757
758 return;
759}
760
762{
763 double dtmp = 0.0;
764
765 for (int i = 0; i < layer.numNeurons; i++)
766 {
767 dtmp = 0.0;
768 for (int j = 0; j < layer.numNeuronsPrevLayer; j++)
769 {
770 dtmp += layer.neurons[i].weights[j] * layerPrev.neurons[j].value;
771 }
772 dtmp += layer.neurons[i].bias;
774 {
775 dtmp /= layer.numNeuronsPrevLayer;
776 }
777
778 layer.neurons[i].x = dtmp;
779 if (layer.activationFunction == AF_IDENTITY)
780 {
781 layer.neurons[i].value = dtmp;
782 layer.neurons[i].dfdx = 1.0;
783 layer.neurons[i].d2fdx2 = 0.0;
784 }
785 else if (layer.activationFunction == AF_TANH)
786 {
787 dtmp = tanh(dtmp);
788 layer.neurons[i].value = dtmp;
789 layer.neurons[i].dfdx = 1.0 - dtmp * dtmp;
790 layer.neurons[i].d2fdx2 = -2.0 * dtmp * (1.0 - dtmp * dtmp);
791 }
792 else if (layer.activationFunction == AF_LOGISTIC)
793 {
794 if (dtmp > EXP_LIMIT)
795 {
796 layer.neurons[i].value = 1.0;
797 layer.neurons[i].dfdx = 0.0;
798 layer.neurons[i].d2fdx2 = 0.0;
799 }
800 else if (dtmp < -EXP_LIMIT)
801 {
802 layer.neurons[i].value = 0.0;
803 layer.neurons[i].dfdx = 0.0;
804 layer.neurons[i].d2fdx2 = 0.0;
805 }
806 else
807 {
808 dtmp = 1.0 / (1.0 + exp(-dtmp));
809 layer.neurons[i].value = dtmp;
810 layer.neurons[i].dfdx = dtmp * (1.0 - dtmp);
811 layer.neurons[i].d2fdx2 = dtmp * (1.0 - dtmp)
812 * (1.0 - 2.0 * dtmp);
813 }
814 }
815 else if (layer.activationFunction == AF_SOFTPLUS)
816 {
817 if (dtmp > EXP_LIMIT)
818 {
819 layer.neurons[i].value = dtmp;
820 layer.neurons[i].dfdx = 1.0;
821 layer.neurons[i].d2fdx2 = 0.0;
822 }
823 else if (dtmp < -EXP_LIMIT)
824 {
825 layer.neurons[i].value = 0.0;
826 layer.neurons[i].dfdx = 0.0;
827 layer.neurons[i].d2fdx2 = 0.0;
828 }
829 else
830 {
831 dtmp = exp(dtmp);
832 layer.neurons[i].value = log(1.0 + dtmp);
833 dtmp = 1.0 / (1.0 + 1.0 / dtmp);
834 layer.neurons[i].dfdx = dtmp;
835 layer.neurons[i].d2fdx2 = dtmp * (1.0 - dtmp);
836 }
837 }
838 else if (layer.activationFunction == AF_RELU)
839 {
840 if (dtmp > 0.0)
841 {
842 layer.neurons[i].value = dtmp;
843 layer.neurons[i].dfdx = 1.0;
844 layer.neurons[i].d2fdx2 = 0.0;
845 }
846 else
847 {
848 layer.neurons[i].value = 0.0;
849 layer.neurons[i].dfdx = 0.0;
850 layer.neurons[i].d2fdx2 = 0.0;
851 }
852 }
853 else if (layer.activationFunction == AF_GAUSSIAN)
854 {
855 double const tmpexp = exp(-0.5 * dtmp * dtmp);
856 layer.neurons[i].value = tmpexp;
857 layer.neurons[i].dfdx = -dtmp * tmpexp;
858 layer.neurons[i].d2fdx2 = (dtmp * dtmp - 1.0) * tmpexp;
859 }
860 else if (layer.activationFunction == AF_COS)
861 {
862 double const tmpcos = cos(dtmp);
863 layer.neurons[i].value = tmpcos;
864 layer.neurons[i].dfdx = -sin(dtmp);
865 layer.neurons[i].d2fdx2 = -tmpcos;
866 }
867 else if (layer.activationFunction == AF_REVLOGISTIC)
868 {
869 dtmp = 1.0 / (1.0 + exp(-dtmp));
870 layer.neurons[i].value = 1.0 - dtmp;
871 layer.neurons[i].dfdx = dtmp * (dtmp - 1.0);
872 layer.neurons[i].d2fdx2 = dtmp * (dtmp - 1.0) * (1.0 - 2.0 * dtmp);
873 }
874 else if (layer.activationFunction == AF_EXP)
875 {
876 dtmp = exp(-dtmp);
877 layer.neurons[i].value = dtmp;
878 layer.neurons[i].dfdx = -dtmp;
879 layer.neurons[i].d2fdx2 = dtmp;
880 }
881 else if (layer.activationFunction == AF_HARMONIC)
882 {
883 layer.neurons[i].value = dtmp * dtmp;
884 layer.neurons[i].dfdx = 2.0 * dtmp;
885 layer.neurons[i].d2fdx2 = 2.0;
886 }
887 layer.neurons[i].count++;
888 dtmp = layer.neurons[i].x;
889 layer.neurons[i].min = min(dtmp, layer.neurons[i].min);
890 layer.neurons[i].max = max(dtmp, layer.neurons[i].max);
891 layer.neurons[i].sum += dtmp;
892 layer.neurons[i].sum2 += dtmp * dtmp;
893 }
894
895 return;
896}
897
899{
900 for (int i = 0; i < numLayers; i++)
901 {
902 for (int j = 0; j < layers[i].numNeurons; j++)
903 {
904 layers[i].neurons[j].count = 0;
905 layers[i].neurons[j].min = numeric_limits<double>::max();
906 layers[i].neurons[j].max = -numeric_limits<double>::max();
907 layers[i].neurons[j].sum = 0.0;
908 layers[i].neurons[j].sum2 = 0.0;
909 }
910 }
911
912 return;
913}
914
916 double* min,
917 double* max,
918 double* sum,
919 double* sum2) const
920{
921 int iNeuron = 0;
922
923 for (int i = 0; i < numLayers; i++)
924 {
925 for (int j = 0; j < layers[i].numNeurons; j++)
926 {
927 count[iNeuron] = layers[i].neurons[j].count;
928 min [iNeuron] = layers[i].neurons[j].min;
929 max [iNeuron] = layers[i].neurons[j].max;
930 sum [iNeuron] = layers[i].neurons[j].sum;
931 sum2 [iNeuron] = layers[i].neurons[j].sum2;
932 iNeuron++;
933 }
934 }
935
936 return;
937}
938
939/*
940void NeuralNetwork::writeStatus(int element, int epoch)
941{
942 char fName[LSTR] = "";
943 FILE* fpn = NULL;
944 FILE* fpw = NULL;
945
946 for (int i = 0; i < numLayers; i++)
947 {
948 sprintf(fName, "nn.neurons.%03d.%1d.%06d", element, i, epoch);
949 fpn = fopen(fName, "a");
950 if (fpn == NULL)
951 {
952 fprintf(stderr, "ERROR: Could not open file: %s.\n", fName);
953 exit(EXIT_FAILURE);
954 }
955 sprintf(fName, "nn.weights.%03d.%1d.%06d", element, i, epoch);
956 fpw = fopen(fName, "a");
957 if (fpw == NULL)
958 {
959 fprintf(stderr, "ERROR: Could not open file: %s.\n", fName);
960 exit(EXIT_FAILURE);
961 }
962 for (int j = 0; j < layers[i].numNeurons; j++)
963 {
964 fprintf(fpn, "%4d %.8f %.8f %.8f %.8f %.8f %.8f\n", j, layers[i].neurons[j].x,
965 layers[i].neurons[j].value, layers[i].neurons[j].dfdx, layers[i].neurons[j].d2fdx2,
966 layers[i].neurons[j].bias, layers[i].neurons[j].dxdG);
967 for (int k = 0; k < layers[i].numNeuronsPrevLayer; k++)
968 {
969 fprintf(fpw, "%4d %4d %.8f\n", j, k, layers[i].neurons[j].weights[k]);
970 }
971 }
972 fclose(fpn);
973 fclose(fpw);
974 }
975
976 return;
977
978}
979*/
980
982{
983 long mem = sizeof(*this);
984 int numNeurons = getNumNeurons();
985
986 mem += (numLayers - 1) * sizeof(int); // weightOffset
987 mem += (numLayers - 1) * sizeof(int); // biasOffset
988 mem += (numLayers - 1) * sizeof(int); // biasOnlyOffset
989 mem += numLayers * sizeof(Layer); // layers
990 mem += numNeurons * sizeof(Neuron); // neurons
991 mem += numWeights * sizeof(double); // weights
992
993 return mem;
994}
995
996vector<string> NeuralNetwork::info() const
997{
998 vector<string> v;
999 int maxNeurons = 0;
1000
1001 v.push_back(strpr("Number of weights : %6zu\n", numWeights));
1002 v.push_back(strpr("Number of biases : %6zu\n", numBiases));
1003 v.push_back(strpr("Number of connections: %6zu\n", numConnections));
1004 v.push_back(strpr("Architecture "));
1005 for (int i = 0; i < numLayers; ++i)
1006 {
1007 maxNeurons = max(layers[i].numNeurons, maxNeurons);
1008 v.push_back(strpr(" %4d", layers[i].numNeurons));
1009 }
1010 v.push_back("\n");
1011 v.push_back("-----------------------------------------"
1012 "--------------------------------------\n");
1013
1014 for (int i = 0; i < maxNeurons; ++i)
1015 {
1016 v.push_back(strpr("%4d", i + 1));
1017 string s = "";
1018 for (int j = 0; j < numLayers; ++j)
1019 {
1020 if (i < layers[j].numNeurons)
1021 {
1022 if (j == 0)
1023 {
1024 s += strpr(" %3s", "G");
1025 }
1026 else if (layers[j].activationFunction == AF_IDENTITY)
1027 {
1028 s += strpr(" %3s", "l");
1029 }
1030 else if (layers[j].activationFunction == AF_TANH)
1031 {
1032 s += strpr(" %3s", "t");
1033 }
1034 else if (layers[j].activationFunction == AF_LOGISTIC)
1035 {
1036 s += strpr(" %3s", "s");
1037 }
1038 else if (layers[j].activationFunction == AF_SOFTPLUS)
1039 {
1040 s += strpr(" %3s", "p");
1041 }
1042 else if (layers[j].activationFunction == AF_RELU)
1043 {
1044 s += strpr(" %3s", "r");
1045 }
1046 else if (layers[j].activationFunction == AF_GAUSSIAN)
1047 {
1048 s += strpr(" %3s", "g");
1049 }
1050 else if (layers[j].activationFunction == AF_COS)
1051 {
1052 s += strpr(" %3s", "c");
1053 }
1054 else if (layers[j].activationFunction == AF_REVLOGISTIC)
1055 {
1056 s += strpr(" %3s", "S");
1057 }
1058 else if (layers[j].activationFunction == AF_EXP)
1059 {
1060 s += strpr(" %3s", "e");
1061 }
1062 else if (layers[j].activationFunction == AF_HARMONIC)
1063 {
1064 s += strpr(" %3s", "h");
1065 }
1066 }
1067 else
1068 {
1069 s += " ";
1070 }
1071 }
1072 v.push_back(s += "\n");
1073 }
1074
1075 return v;
1076}
1077
1079{
1081
1082 if (c == "l") a = NeuralNetwork::AF_IDENTITY;
1083 else if (c == "t") a = NeuralNetwork::AF_TANH;
1084 else if (c == "s") a = NeuralNetwork::AF_LOGISTIC;
1085 else if (c == "p") a = NeuralNetwork::AF_SOFTPLUS;
1086 else if (c == "r") a = NeuralNetwork::AF_RELU;
1087 else if (c == "g") a = NeuralNetwork::AF_GAUSSIAN;
1088 else if (c == "c") a = NeuralNetwork::AF_COS;
1089 else if (c == "S") a = NeuralNetwork::AF_REVLOGISTIC;
1090 else if (c == "e") a = NeuralNetwork::AF_EXP;
1091 else if (c == "h") a = NeuralNetwork::AF_HARMONIC;
1092 else
1093 {
1094 throw runtime_error("ERROR: Unknown activation function.\n");
1095 }
1096
1097 return a;
1098}
#define EXP_LIMIT
ActivationFunction
List of available activation function types.
Definition: NeuralNetwork.h:33
@ AF_RELU
(NOT recommended for HDNNPs!)
Definition: NeuralNetwork.h:45
int getNumConnections() const
Return total number of connections.
Layer * inputLayer
Pointer to input layer.
void setInput(double const *const &input) const
Set neural network input layer node values.
int getNumNeurons() const
Return total number of neurons.
int * biasOnlyOffset
Offset adress of biases per layer in bias only array.
void modifyConnections(ModificationScheme modificationScheme)
Change connections according to a given modification scheme.
int numLayers
Total number of layers (includes input and output layers).
void calculateDEdb(double *dEdb) const
Calculate derivative of output neuron with respect to biases.
int getNumWeights() const
Return number of weights.
void setConnections(double const *const &connections)
Set neural network weights and biases.
void writeConnections(std::ofstream &file) const
Write connections to file.
bool normalizeNeurons
If neurons are normalized.
void calculateDFdc(double *dFdc, double const *const &dGdxyz) const
Calculate "second" derivative of output with respect to connections.
void propagateLayer(Layer &layer, Layer &layerPrev)
Propagate information from one layer to the next.
void allocateLayer(Layer &layer, int numNeuronsPrevLayer, int numNeurons, ActivationFunction activationFunction)
Allocate a single layer.
int * weightOffset
Offset adress of weights per layer in combined weights+bias array.
void initializeConnectionsRandomUniform(unsigned int seed)
Initialize connections with random numbers.
int * biasOffset
Offset adress of biases per layer in combined weights+bias array.
void calculateD2EdGdc(int index, double const *const &dEdb, double *d2EdGdc) const
Calculate second derivative of output neuron with respect to input neuron and connections.
void getNeuronStatistics(long *count, double *min, double *max, double *sum, double *sum2) const
Return gathered neuron statistics.
int numBiases
Number of NN biases only.
void resetNeuronStatistics()
Reset neuron statistics.
ModificationScheme
List of available connection modification schemes.
Definition: NeuralNetwork.h:60
@ MS_ZEROOUTPUTWEIGHTS
Set all weights connecting to the output layer to zero.
Definition: NeuralNetwork.h:64
@ MS_ZEROBIAS
Set all bias values to zero.
Definition: NeuralNetwork.h:62
@ MS_PRECONDITIONOUTPUT
Apply preconditioning to output layer connections.
@ MS_FANIN
Normalize weights via number of neuron inputs (fan-in).
Definition: NeuralNetwork.h:74
@ MS_GLOROTBENGIO
Normalize connections according to Glorot and Bengio.
Definition: NeuralNetwork.h:90
@ MS_NGUYENWIDROW
Initialize connections according to Nguyen-Widrow scheme.
void getConnections(double *connections) const
Get neural network weights and biases.
int numConnections
Number of NN connections (weights + biases).
void propagate()
Propagate input information through all layers.
void calculateDEdc(double *dEdc) const
Calculate derivative of output neuron with respect to connections.
void setNormalizeNeurons(bool normalizeNeurons)
Turn on/off neuron normalization.
int getNumBiases() const
Return number of biases.
void calculateDEdG(double *dEdG) const
Calculate derivative of output neuron with respect to input neurons.
void calculateDxdG(int index) const
Calculate derivative of neuron values before activation function with respect to input neuron.
Layer * layers
Neural network layers.
int numWeights
Number of NN weights only.
void getOutput(double *output) const
Get neural network output layer node values.
Layer * outputLayer
Pointer to output layer.
int numHiddenLayers
Number of hidden layers.
std::vector< std::string > info() const
Print neural network architecture.
Definition: Atom.h:29
string strpr(const char *format,...)
String version of printf function.
Definition: utility.cpp:90
vector< string > createFileHeader(vector< string > const &title, vector< size_t > const &colSize, vector< string > const &colName, vector< string > const &colInfo, char const &commentChar)
Definition: utility.cpp:111
NeuralNetwork::ActivationFunction activationFromString(std::string c)
Convert string to activation function.
void appendLinesToFile(ofstream &file, vector< string > const lines)
Append multiple lines of strings to open file stream.
Definition: utility.cpp:225
One neural network layer.
int numNeurons
Number of neurons in this layer .
Neuron * neurons
Array of neurons in this layer.
ActivationFunction activationFunction
Common activation function for all neurons in this layer.
int numNeuronsPrevLayer
Number of neurons in previous layer .
double * weights
NN weights assigned to neuron.
double bias
Bias value assigned to this neuron (if this is neuron this bias value is ).
double max
Maximum neuron value over data set (neuron statistics).
double sum
Sum of neuron values over data set (neuron statistics).
double dxdG
Derivative of neuron value before application of activation function with respect to input layer neur...
double value
Neuron value.
long count
How often the value of this neuron has been evaluated.
double d2fdx2
Second derivative of activation function with respect to its argument .
double dfdx
Derivative of activation function with respect to its argument .
double min
Minimum neuron value over data set (neuron statistics).
double x
Neuron value before application of activation function.
double sum2
Sum of squared neuron values over data set (neuron statistics).